Wednesday, October 29, 2008

Quick Tip - Console Goodies

I just want to mention two quick little goodies for the rails console.

Tip #1 - Reloading

Have you ever been running the console and after modifying your source you notice that the console has not picked up your changes? This usually occurs when you adding/removing/editing associations on a model, messing around with your vendor or lib directory, changed an environment config or anything else that only gets loaded once.

Luckily there is a way to quickly reload your whole console environment without having to quit and restart saving you precious seconds. Actually when I used to develop in a windows environment starting up the console would take a very long time so this would save more than just a few seconds.


$ ruby script/console
Loading development environment (Rails 2.1.1)
>> User.first.posts
NoMethodError: undefined method `posts' for #<Class:0xb6f55a08>
# Now add the posts association on User
>> reload!
Reloading...
=> true
>> User.first.posts
=> [#<Post id: 1 ....>]

As you can see you just need to run the unsubtle command reload! to reload the environment.

Tip #2 - Sandbox

Have you ever want to muck around in your development database or dare I say production database and wished your temporary changes would not persist? Perhaps you wanted to test that new :dependent => :destroy association or perhaps you wanted to be evil (if only for a second) and destroy all the existing users just to make you feel powerful. Here's how to do it.


$ ruby script/console production --sandbox
Loading production environment in sandbox (Rails 2.1.1)
Any modifications you make will be rolled back on exit
>> User.count
=> 214
>> User.destroy_all #Insert evil laugh here
=> [#<User id: .... ]
>> User.count
=> 0
>> exit

$ ruby script/console production --sandbox
Loading production environment in sandbox (Rails 2.1.1)
Any modifications you make will be rolled back on exit
>> User.count
=> 214

All you need to do here is add the --sandbox flag when starting up the console. Its basically like having a huge transaction block around your whole console session and by exiting you are throwing and exception and everything gets rolled back.

No comments: