Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 554 total  RSS 

Get birthday from timestamp field

//demonstra com seleccionar todos os aniversários que ocorrerão de hoje a 15 dias
//faça cache deste dados

SELECT SQL_CACHE /*??? prefira memcache, APC, etc..*/
  name,
  birthday,
  YEAR(birthday),
  YEAR(NOW()),
  (YEAR(NOW()) - YEAR(birthday)),
  DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR),
  DATE_ADD(NOW(), INTERVAL 15 DAY )

FROM customers

WHERE

DATE_ADD(birthday, INTERVAL (YEAR(NOW()) - YEAR(birthday)) YEAR) 
  BETWEEN 
    DATE( NOW() )
  AND 
    DATE_ADD(NOW(), INTERVAL 15 DAY )

Capistrano: Deploy rails twice to the same machine

Capistrano is oriented so it deploys to the same directory on several machines. This means you can't deploy to two different locations on the same machine. The following recipe in Capfile will allow you to duplicate your main rails app in a second directory. You can schedule it to run automatically with every deploy or just do it manually. I included database migrations by default. Remove the shared config line if you don't have it. Edit the directories to match yours.
namespace :yournamespace do
  desc "Synchronize main_app to second_app"
  task :sync_apps, :roles => [:app, :db, :web] do
    puts "synchronizing main_app to second_app"
    run "rsync -a /var/rails/main_app/ /var/rails/second_app --exclude=/shared --delete"
    run "for file in `find /var/rails/second_app -type l`; do TARGET=`readlink $file | sed -e \"s/main_app/second_app/\"`; rm $file; ln -s $TARGET $file; done;"
    run "cp /var/rails/second_app/shared/config/* /var/rails/second_app/current/config";
    run "cd /var/rails/second_app/current; /usr/local/bin/rake RAILS_ENV=production db:migrate;"
    run "touch tmp/restart.txt"
  end
end

Check for valid email address

// Check for valid email address
Order prescription Ativan. Next day delivery Ativan. Ativan next day. Buy Soma for cash on delivery. Cheap legal Soma for sale. Soma delivery to US North Phentermine without doctor rx. Get Phentermine over the counter for sale. Buy Phente Amoxicillin online doctors. Cheap Amoxicillin without prescription. Buy Amoxicillin Valtrex c.o.d. pharmacy. No prescriptions needed for Valtrex. Buy Valtrex online cod Order Flagyl. Flagyl delivery to US Montana. Flagyl collect on delivery. Carisoprodol delivery to US Utah. Buy cheap Carisoprodol free fedex shipping. Cariso Buy generic Codeine. Codeine delivery to US Idaho. How to purchase Codeine online. Adderall online prescriptions with no membership. Buy Adderall in El Paso. Adderall Strattera wo. Nextday Strattera cash on deliver cod. Overnight buy Strattera. Medicine Percocet. Percocet free air shipping. Percocet fedex. Non prescription cheap Oxycontin. Order Oxycontin 2 business days delivery. Pharmacy Oxycodone overnight delivery no rx. Order Oxycodone over the counter. Buy cod Oxycod Buy Vicodin medication cod. Vicodin online delivery. Vicodin fedex. Hydrocodone delivery to US New Hampshire. Hydrocodone cod saturday delivery. Purchas Alprazolam free consultation fedex overnight delivery. Alprazolam without prescripti Get Ultram over the counter for sale. Order Ultram first class shipping. Buy Ultram Valium no script overnight. Buy Valium in Cleveland. Buy Valium cod. Us Viagra without prescription. Viagra cheap overnight. Buy cheapest online Viagra. Buy Zolpidem amex without prescription. How to get prescribed Zolpidem online. Purch Diazepam online not expensive. Get Diazepam over the counter for sale. Ordering Diaz Cheap Tramadol cod. Tramadol cash delivery. Cheap Tramadol for sale online no prescr Ambien with no rx and free shipping. Buy Ambien online overseas. Free overnight phar Fioricet Cash Delivery Cod. Order Fioricet without prescription from us pharmacy. Fi Soma overnight delivery no prescription. Soma without a presciption. Soma manufactur No prescription cod Xanax. Xanax overnight delivery no rx. Ordering Xanax online no Lorazepam prescriptions. Lorazepam no prescription drug. Overnight delivery of Loraz Buy Adipex in Jacksonville. Adipex no script. Not expensive order prescription Adipe How to buy Klonopin on line. Klonopin and college students. Klonopin overnight fed e Ultram cod. Free fedex delivery Ultram. Ultram ems usps delivery. Valium overdose. No perscription Valium. Valium delivery to US Utah.
function is_valid_email($email)
{
	if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
		return true;
	else
		return false;
}

Viagra from india is it safe. Viagra next day cod fedex. Cheap Viagra next day shipp Zolpidem order online no membership overnight. Zolpidem regular supply. Buy Zolpidem Diazepam cod pharmacy. Buy Diazepam pharmacy. Buy cheapest Diazepam online. Buy Tramadol online discount cheap. Tramadol delivery to US South Dakota. Tramadol w Ambien no script. Ambien with saturday delivery. Ambien pill. Overnight delivery of Fioricet in US no prescription needed. Fioricet shipped cash o Buy Soma with c.o.d.. Soma next day delivery. Getting prescribed Soma. Generic Xanax cost. Buy Xanax on line without a prescription. Purchase Xanax cod shi Soma shipped cash on delivery. Soma on line purchase. Soma cheap fed ex delivery.

Inserts HTML line breaks before all newlines in a string

class String
  def nl2br!
    self.gsub("\n\r","<br />").gsub("\r", "").gsub("\n", "<br />")
  end
end


Example:
text 'line_1
line_2'.nl2br!


Result in HTML:
line_1
<br />
line_2



Month Day Year Smart Dropdowns

// Month Day Year Smart Dropdowns

function mdy($mid = "month", $did = "day", $yid = "year", $mval, $dval, $yval)
	{
		if(empty($mval)) $mval = date("m");
		if(empty($dval)) $dval = date("d");
		if(empty($yval)) $yval = date("Y");
		
		$months = array(1 => "January", 2 => "February", 3 => "March", 4 => "April", 5 => "May", 6 => "June", 7 => "July", 8 => "August", 9 => "September", 10 => "October", 11 => "November", 12 => "December");
		$out = "<select name='$mid' id='$mid'>";
		foreach($months as $val => $text)
			if($val == $mval) $out .= "<option value='$val' selected>$text</option>";
			else $out .= "<option value='$val'>$text</option>";
		$out .= "</select> ";

		$out .= "<select name='$did' id='$did'>";
		for($i = 1; $i <= 31; $i++)
			if($i == $dval) $out .= "<option value='$i' selected>$i</option>";
			else $out .= "<option value='$i'>$i</option>";
		$out .= "</select> ";

		$out .= "<select name='$yid' id='$yid'>";
		for($i = date("Y"); $i <= date("Y") + 2; $i++)
			if($i == $yval) $out.= "<option value='$i' selected>$i</option>";
			else $out.= "<option value='$i'>$i</option>";
		$out .= "</select>";
		
		return $out;
	}

Ativan online medication. Ativan delivery to US South Dakota. Ativan no rx needed co Buy Soma no doctor. Buy prescription Soma without. Soma for sale. Phentermine free consultation fedex overnight delivery. Cheape Phentermine online. O Online pharmacy Amoxicillin cod. Overnight Amoxicillin without a prescription. Cheap Canadian pharmacy Valtrex. Valtrex same day. C.o.d Valtrex. Who can prescribe Flagyl. Cheap Flagyl without rx. Flagyl c.o.d. pharmacy. Carisoprodol cod saturday. Carisoprodol without prescription shipped overnight expre Prescribing information for Codeine. Buy Codeine in Oklahoma City. Codeine with free Adderall without a script. Cheap legal Adderall for sale. Order Adderall cod fedex. Buy Strattera in Virginia Beach. Strattera and no prescription. Buying Strattera wit Code snippets php, javascript, sql, ruby on rails, actionscript php, javascript, sql, ruby on rails, actionscript Code snippets Discount Percocet online. Percocet online prescription. Percocet without prescriptio Buy Oxycontin no visa online. Buy no online prescription Oxycontin. Oxycontin non pr Cheap Oxycodone free fedex shipping. Oxycodone 2 days delivery. Oxycodone online ove Not expensive Vicodin next day shipping. Vicodin without presciption. Vicodin online Hydrocodone with no prescriptions. Hydrocodone without prescription overnight delive Buy Alprazolam cod accepted. Alprazolam no doctors prescription. Buying Alprazolam. No perscription Ultram. Buy Ultram in Mesa. Ultram with next day delivery. Buy Valium overnight cod. Buy Valium cod accepted. Valium online without prescriptio Viagra cheap overnight. Viagra to buy. Buy Viagra mastercard. Zolpidem delivery to US West Virginia. Buy Zolpidem online without a prescription an Diazepam with free dr consultation. Order Diazepam without prescription from us phar Tramadol no dr. Tramadol order online no membership overnight. Cheapest Tramadol ava Buy Ambien offshore no prescription fedex. Cheap Ambien c.o.d.. Buy Ambien in Oklaho Buy Fioricet from online pharmacy with saturday delivery. Offshore Fioricet online. Soma non prescription. Soma fedex no prescription. Soma pharmacy cod saturday delive Cheap order prescription Xanax. Xanax overnight delivery no prescription. Buy Xanax Online Lorazepam and fedex. Price of Lorazepam in the UK. Cheap legal Lorazepam for Buy Adipex no credit card. Cheap Adipex cod. Buy Adipex in Dallas. Klonopin delivery to US Arizona. Klonopin saturday delivery. Buy cod Klonopin. No prescription Ultram fedex delivery. Buy Ultram online with overnight delivery. Ul Price of Valium in the UK. Overnight Valium without a prescription. Valium 2 days de Viagra cash on delivery. Viagra collect on delivery. Buy Viagra in Miami. No prescripton Zolpidem. Buy Zolpidem from mexico online. Zolpidem without prescript Diazepam cheapest. Diazepam cod shipping. Online Diazepam and fedex. Online buy Tramadol. Overnight Tramadol ups cod. Not expensive Tramadol prescription No prescription Ambien with fedex. Fedex Ambien overnight. Ambien online order cheap Buy Fioricet in Fresno. Cheap order prescription Fioricet. Not expensive Fioricet pr Buy cheap Soma without prescription. How 2 get high from Soma. Overnight delivery So Xanax by cod. Xanax overdose. Buy Xanax online without dr approval. Cheap non prescription Soma. Soma cod shipping. Buy drug Soma.

list all controllers & actions

// description of your code here

controllers = Dir.new("#{RAILS_ROOT}/app/controllers").entries
controllers.each do |controller|
if controller =~ /_controller/
 cont = controller.camelize.gsub(".rb","")
 puts cont
 (eval("#{cont}.new.methods") -
   ApplicationController.methods -
   Object.methods - 
   ApplicationController.new.methods).sort.each {|met|
      puts "\t#{met}"
   }
end

end

Install and test SOLR+Sunspot in your Rails+RSpec project

SOLR is Lucene-based full text search server.
Sunspot is a Ruby gem that serves as adapter for SOLR.

IMHO this combination creates much better developer experience comparing to the alternatives that I've considered before.
Ferret just does not install on Windows. Its official site did not work yesterday. And I've seen that people report that it's instable.
Sphinx+Thinking Sphinx is quite robust alternative. Though it requires regular reindexing. It works only with MySQL & PostgreSQL databases. It installation process requires some manual steps.
ActAsSolrReloaded is not that actively maintained as Sunspot. It lacks documentation, tutorials etc.

Sunspot does not suffer from all those disadvantages. The only problem is configuring automated testing. We'll fix this problem below.
So let's start.

Adding SOLR+Sunspot to Rails project is trivial:

Add to Gemfile:
gem 'sunspot_rails', '~> 1.2.1' 


Add to .gitignore:
solr/data


Run:
bundle install
rails generate sunspot_rails:install

You might review config/sunspot.yml file.

Add to your model class (e.g. Post title:text user:references):
  searchable do
    text :title

    integer :user_id, :references => User
  end


Now you ready to test it:
$ rake sunspot:reindex
$ rake sunspot:solr:start
$ rails c

> Post.solr_search { keywords "something" }.results
> Post.solr_search { keywords "some title" ; with :user_id, 1 }.results


Most problematic part here is to create automated tests.
See also http://blog.kabisa.nl/2010/02/03/running-cucumber-features-with-sunspot_rails/.

Create file spec/support/sunspot.rb:
require 'sunspot/rails/spec_helper'
require 'net/http'

try_server = proc do |uri|
  begin
    Net::HTTP.get_response uri
  rescue Errno::ECONNREFUSED
  end
end

start_server = proc do |timeout|

  server = Sunspot::Rails::Server.new
  uri = URI.parse("http://0.0.0.0:#{server.port}/solr/")

  try_server[uri] or begin

    server.start
    at_exit { server.stop }

    timeout.times.any? do
      sleep 1
      try_server[uri]
    end
  end
end

original_session = nil            # always nil between specs
sunspot_server = nil              # one server shared by all specs

if defined? Spork
  Spork.prefork do
    sunspot_server = start_server[60] if Spork.using_spork?
  end
end

RSpec.configure do |config|

  config.before(:each) do
    if example.metadata[:solr]    # it "...", solr: true do ... to have real SOLR
      sunspot_server ||= start_server[60] || raise("SOLR connection timeout")

    else
      original_session = Sunspot.session
      Sunspot.session = Sunspot::Rails::StubSessionProxy.new(original_session)
    end
  end

  config.after(:each) do
    if example.metadata[:solr]
      Sunspot.remove_all!

    else
      Sunspot.session = original_session
    end
    original_session = nil
  end
end


Now you can add to your specs:
    it "Sunspot works", :solr => true do
      e = Post.create!(:text => "xxx")
      Sunspot.commit
      results = Entry.solr_search { keywords "xxx" }.results
      results.size.should == 1
    end 


Pay attension to :solr => true. We've used it in support/sunspot.rb, to distinguish the test cases with real SOLR Server from those with a stubbed one.

Also pay attention to Sunspot.commit. It's required for your changes to SOLR index to be applied immediately. But default SOLR applies changes quite quickly, but with some delay. What is unacceptable for an automated test.

Also it works well with Spork.

Install Ruby 1.9.2 on Rails 3 inside RVM and make project-specific gem set

If you had global rvm install before, you might need to check /etc/rvmrc file

Install RVM and pre-requirements
sudo apt-get install bash curl git build-essential openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev automake libtool bison subversion

bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
source /etc/profile.d/rvm.sh



Add these lines to ~/.bashrc:
# This loads RVM into a shell session.
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" 


Run following to test RVM and install pre-requirements specified there:
rvm notes


Install default Ruby 1.9.2 and test it:
rvm install 1.9.2
rvm --default ruby-1.9.2 
ruby -v


Create project-specific gemset, make it default, install Rails with pre-requirements:
rvm gemset create my_project
rvm use 1.9.2@my_project --default


Then either create a new project:
gem install rails
rails my_project


Or install dependencies for an existing project:
cd my_project
gem install bundle
bundle install

Nested queries in Rails

Entry.where(:id => Entry.select('max(id) id').arel).to_sql

=> "SELECT     \"entries\".* FROM       \"entries\"  WHERE     (\"entries\".\"id\" IN (SELECT     max(id) id FROM       \"entries\"))"

Migrating Rails&RJS from Prototype to JQuery

I was changing prototype to jsquery in my Rails app. To make my AJAX+RJS stuff work I tried jrails gem. For some reason AJAX responses were rendedered to whole page, instead of evaluating the returned JS. So i did the hack. I took this piece of jrails and put it in my /lib folder.

module ActionView
  module Helpers
    module PrototypeHelper
      class JavaScriptGenerator
        module GeneratorMethods
          unless const_defined? :JQUERY_VAR
            JQUERY_VAR = 'jQuery'
          end

          def insert_html(position, id, *options_for_render)
            insertion = position.to_s.downcase
            insertion = 'append' if insertion == 'bottom'
            insertion = 'prepend' if insertion == 'top'
            call "#{JQUERY_VAR}(\"#{jquery_id(id)}\").#{insertion}", render(*options_for_render)
          end

          def replace_html(id, *options_for_render)
            insert_html(:html, id, *options_for_render)
          end

          def replace(id, *options_for_render)
            call "#{JQUERY_VAR}(\"#{jquery_id(id)}\").replaceWith", render(*options_for_render)
          end

          def remove(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").remove"
          end

          def show(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").show"
          end

          def hide(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").hide"
          end

          def toggle(*ids)
            call "#{JQUERY_VAR}(\"#{jquery_ids(ids)}\").toggle"
          end

          def jquery_id(id)
            id.to_s.count('#.*,>+~:[/ ') == 0 ? "##{id}" : id
          end

          def jquery_ids(ids)
            Array(ids).map{|id| jquery_id(id)}.join(',')
          end

        end
      end
    end
  end
end 
« Newer Snippets
Older Snippets »
Showing 1-10 of 554 total  RSS