Sunday, August 19, 2007

Evil Rails Console Gotcha: reload!

Rails' console has a great feature: reload!. Introduced in Rails 1.1, it allows you to update your console's Rails app with any changes you've made on the filesystem.

However, if you create an object, like an ActiveRecord model, and then return to your Rails console to type reload!, it'll only reload the code. It won't reinstantiate any existing objects. And because of the dynamic way that methods get attached to ActiveRecord models, the instantiation process is an important step. So you can make a change in an ActiveRecord model, switch back to the console, hit reload!, and get nothing new at all.

It's probably possible to write some Ruby which queries ObjectSpace for ActiveRecord models, loads their attributes off into a hash, and then reinstantiates them - but making something like that portable could take some serious wizardry. I leave it as an exercise for the reader who is smarter than me. It's a lot easier to just remember, after you hit reload!, you may in some cases have to reinstantiate some of your objects.

It's not perfect, but it still beats starting over entirely from scratch.

1 comment:

  1. Your post inspired me to write about my own favorite frustration with reload! and the Rails console: it doesn't even reload all of your code


Note: Only a member of this blog may post a comment.