Tatva-Artha

meaning of "it"

Rails monkeypatching to pin-point offending code

without comments

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”.

http://www.tatvartha.com/wp-content/plugins/sociofluid/images/digg_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/reddit_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/stumbleupon_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/delicious_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/google_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/twitter_16.png

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Written by Sharad

September 25th, 2009 at 8:17 pm

Posted in All

Leave a Reply