Console Shortcut
(Mon Sep 03, 2007) [/Rails] #
In honor of Labor Day, here's a hack that might save you some. I spend
a lot of time in the Rails console, and most of that time I'm finding
stuff. Typing find is so... laborious. But drop this
in your ~/.irbrc file, and your work is made light.
# Creates shortcut methods for finding models.
def define_model_find_shortcuts
model_files = Dir.glob("app/models/**/*.rb")
table_names = model_files.map { |f| File.basename(f).split('.')[0..-2].join }
table_names.each do |table_name|
Object.instance_eval do
define_method(table_name) do |*args|
table_name.camelize.constantize.send(:find, *args)
end
end
end
end
# Called when the irb session is ready, after
# the Rails goodies used above have been loaded.
IRB.conf[:IRB_RC] = Proc.new { define_model_find_shortcuts }
Now you can find stuff using shortcut methods that are named after your models:
$ script/console
Loading development environment.
>> event(1)
>> person(:all)
>> tag(:all, :conditions => {:name => "it"})
You get the picture. Just a simple, naive hack that pays for itself four characters at a time.
