Monkey Patching ActiveRecord Models

Dan Bridges
Parallel Thinking
Published in
1 min readApr 3, 2020

While working on a Rails application I had a need to override a method on an ActiveRecord model, but only in the development environment. I could conditionally include my monkey patched module in the class definition, like so:

class MyModel < ApplicationRecord
include MyDevOverrides if Rails.env.development?
end

This works, but I prefer to keep environment specific information in initializers. At first I tried calling include on the class with my module, but that doesn't work correctly due to Rail's autoloading behavior. The trick is to use ActiveSupport::Reloader.to_prepare like so:

module MyDevOverrides
...
end

ActiveSupport::Reloader.to_prepare do
MyModel.include MyDevOverrides
end

--

--

Dan Bridges
Parallel Thinking

Software developer at Beezwax Datatools and former researcher in Physics & Neuroscience.