10 Rails console tricks
Invoking helper methods
>> helper.number_to_currency('123.45')
Method definition finder (irb)
>> helper.method(:truncate)
=> #<Method: ActionView::Base(ActionView::Helpers::TextHelper)#truncate>
>> "".method(:camelize)
=> #<Method: String(ActiveSupport::CoreExtensions::String::Inflections)#camelize>
Method finder (irb)
$ gem install what_methods
>> require 'what_methods'
>> "foo ".what? "foo"
"foo ".chop! == "foo"
"foo ".chop == "foo"
"foo ".strip! == "foo"
"foo ".strip == "foo"
"foo ".rstrip! == "foo"
"foo ".rstrip == "foo"
=> ["chop!", "chop", "strip!", "strip", "rstrip!", "rstrip"]
Method lookup (irb)
>> "".methods.grep(/case/).sort
=> ["camelcase", "casecmp", "downcase", "downcase!", "swapcase", "swapcase!", "titlecase", "upcase", "upcase!"]
Avoid screenfuls of objects (irb)
>> people = Person.all; nil
=> nil
Rollback database modifications on exit
$ ./script/console --sandbox
Last expression (irb)
>> Person.first
=> #<Person id: 1, first_name: "Dejan" ... >
>> _.first_name
=> "Dejan"
Reload code changes
>> reload!
Better object format (irb)
>> y User.first
--- !ruby/object:User
attributes:
hashed_password: 123456789cde83xa9b86e36e4627360
last_seen_at: 2009-12-09 13:16:44
username: dejan
id: "1"
created_at: 2007-01-14 17:30:00
attributes_cache: {}
script/console logging
You need this.
>> User.cached(:first)
==> Got User:first from cache. (0.10173)
User Load (300.1ms) SELECT * FROM `users` LIMIT 1
==> Set User:first to cache. (0.01512)
=> #<User id: 1, username: "dejan", ... >
>> User.cached(:first)
==> Got User:first from cache. (0.00061)
=> #<User id: 1, username: "dejan", ... >
>> User.expire_cache(:first)
==> Deleted User:first from cache. (0.00059)
=> true
- http://stackoverflow.com/questions/123494/whats-your-favourite-irb-trick
- http://slash7.com/2006/12/21/secrets-of-the-rails-console-ninjas
- http://drnicwilliams.com/2006/10/12/my-irbrc-for-consoleirb
- http://railscasts.com/episodes/48-console-tricks
- http://pablotron.org/software/wirble