Rails integration test: setting the host

10/02/2009
def test_something_else
  sess = open_session
  sess.host = "foo.bar.com"
end
No Comments

Installing the mysql gem on OS X Leopard

3/02/2009

First make sure you have the MySQL client libraries installed, then:

sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config

Source: http://weblog.rubyonrails.com/2007/10/26/today-is-leopard-day

No Comments

Ruby: convert Unix timestamp to date

4/07/2008
t = Time.at(1215163257)
puts t.to_date
>> 2008-07-04
No Comments

Multi-line strings in Ruby

3/07/2008
numbers = %{
one
two 
three
}
No Comments

Mongrel init script

27/06/2008
#!/usr/bin/env ruby
 
app_dir = '/srv/www'
 
apps = {
  'ladybird' => 8001
}
 
if ['stop', 'restart'].include? ARGV.first
  apps.each do |path, port|
    path = File.join app_dir, path
    puts "Stopping #{path}..."
    `mongrel_rails stop -c #{path}/current -P log/mongrel.pid`
  end
end
 
if ['start', 'restart'].include? ARGV.first
  apps.each do |path, port|
    path = File.join app_dir, path
    puts "Starting #{path} on #{port}..."
    `mongrel_rails start -d -p #{port} -e production -c #{path}/current -P log/mongrel.pid`
  end
end
 
unless ['start', 'stop', 'restart'].include? ARGV.first
    puts "Usage: mongrel {start|stop|restart}"
    exit
end
No Comments

ActiveRecord: has the object been saved to the database yet?

25/06/2008

Cleaner than checking if the value of fruit.id is nil:

fruit.new_record?
No Comments

Ruby: strip all non-numeric characters from a string

14/12/2006

Use gsub.

>> str = "222, 000*"
=> "222, 000*"
>> str.gsub!(/[^0-9]/,'')
=> "222000"
No Comments

Ruby: case statements

11/12/2006

Known as switch statements in PHP.

case @user.age
when 0 .. 2
  "baby"
when 3 .. 6
  "little child"
when 7 .. 12
  "child"
when 12 .. 18
  # Note: 12 already matched by "child"
  "youth"
else
  "adult"
end

The when and else keywords are not indented – they line up with the opening case.

Docs: http://www.ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#case

No Comments

Ruby: generate a random password

24/11/2006
def random_password(size=8)
  chars = (('a'..'z').to_a + ('0'..'9').to_a) - %w(i o 0 1 l 0)
  (1..size).collect{|a| chars[rand(chars.size)] }.join
end
No Comments

substr in Ruby

9/10/2006

To get the substring of a string, you can use the array index operator:

@controller_name[0,5]

…or slice:

@controller_name.slice(0,5)

…where 0 is the index to start at, and 5 is the length of the substring to be extracted.

More info: http://www.rubycentral.com/ref/ref_c_string.html#_ob_cb

No Comments