openSUSE:Appliances events workshop Nuremberg 2010 general Rails tips and tricks

Jump to: navigation, search

General

  • History for irb and rails console:
~/.irbrc:
require 'irb/completion'
require 'irb/ext/save-history'
ARGV.concat [ "--readline", "--prompt-mode", "simple" ]
IRB.conf[:SAVE_HISTORY] = 100
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-save-history"

Coding

  • present?
!foo.blank? can also be written as foo.present?
  • find_or_(create|initialize)_by

Instead of

foo = Foo.find_by_name(bar)
if !foo
  foo = Foo.new(:name => bar)   # Or Foo.create(:name => bar)
end

You can also write

foo = Foo.find_or_initialize_by_name(:name => bar)   # Or Foo.find_or_create_by_name(:name => bar)
  • || and ||=
# Not so good
foo = bar
if !foo
  foo = get_foo
end
# Better
foo = bar || get_foo
# And accordingly
foo ||= get_foo