Home | Archives

Dec 08

Automatic Code Reloading in Rails Console

  • rails
  • ruby

Isn’t it nice how Rails server automatically reloads your code before each request in the development? Wouldn’t it be nice if Rails console worked the same way? Sure, you can manually call reload!, but gems like active_reload – or Rails 3.2 itself – make reloading a near no-op most of the time, so we really don’t have to be so stingy about reloading.

Here’s how you can get IRB to reload your code automatically.

Add the following to an initializer (e.g. config/initializers/irb_reloading.rb, or whatever your project’s conventions dictate):

if defined?(IRB::Context) && !defined?(Rails::Server) && Rails.env.development?
  class IRB::Context
    def evaluate_with_reloading(line, line_no)
      reload!(true)

      evaluate_without_reloading(line, line_no)
    end
    alias_method_chain :evaluate, :reloading
  end

  puts "=> IRB code reloading enabled"
end

Now you’re ready to go – your code will be reloaded before IRB evaluates a line, so you can change files and see the changes immediately, without restarting Rails console or calling reload!.


Additional Notes

  • If you are using a version of the ruby-debug gem that overrides IRB::Context#evaluate (version 0.10.4 does, other versions might do so as well), you’ll need to require 'ruby-debug' before the meat of this initializer runs – e.g. as the first line inside the if check.
  • Not using IRB? This idea shouldn’t be difficult to adapt to Pry, or whatever Ruby shell you might be using.

 

blog comments powered by Disqus