Rails monkeypatching to pin-point offending code
Monkey-patching is generally a bad thing but it can help you pin point offending code. I ran into a situation today where I was getting logger to be nil inside ActiveRecord model class. Normally, every ActiveRecord object has reference to logger for logging purposes. This logger is ideally never nil.
I knew, this must be a code somewhere in my codebase that must be setting it to nil. The trouble with rails’ dynamic nature is you can’t find reference to a method call in your IDE. You are left with brute-force find/grep … or monkey patching.
I was able to pin-point offending code using following code:
# this can go in environment.rb temporarily module ActiveRecord class Base class << self def logger_with_nil_check=(new_logger) raise "logger cannot be set to nil" if !new_logger logger_without_nil_check end alias_method_chain :logger=, :nil_check end end end
Isn’t this what they call “developer freedom”.
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.





