How to monkey-patch code that gets auto-loaded in Rails?

pupeno picture pupeno · Dec 16, 2010 · Viewed 9.5k times · Source

I'm monkey-patching a Rails engine with something like:

SomeClass.class_eval do
  # ...
end

The first time I hit the web site, on development mode at least, it works, but the second time it's like my patch never existed. I presume it's Rails auto-reloading the engine (which is installed in vendor/) and not reloading my code. This is Rails 2.3.

Any ideas how to do it so that my code also gets reloaded?

Answer

James H picture James H · Oct 6, 2011

EDIT: This solution only works for Rails 3+ since it's dependent on some functionality in Rails::Railtie. Put this code in an initializer.

This question is quite old, but here's a solution I found:

Rails.configuration.to_prepare do
  SomeClass.class_eval do
    # ...
  end
end

This forces Rails to reload the class on every request in development mode, but only once in production.