How to Monkey Patch in Ruby on Rails?

jaycode picture jaycode · Sep 30, 2010 · Viewed 7.2k times · Source

Lets use a real world example.

I want to monkey patch WillPaginate::LinkRenderer.to_html method.

So far I have tried:

  1. Created a file in folder: lib/monkeys/will_paginate_nohtml.rb
  2. Added in config/environments.rb: require 'monkeys/will_paginate_nohtml' at the end of the file
  3. Inside that file, this was my code:

e

module Monkeys::WillPaginateNohtml
  def to_html
    debugger
    super
  end
end

WillPaginate::LinkRenderer.send(:include, Monkeys::WillPaginateNohtml)

But somehow, debugger doesn't get passed through. Looks like the patching failed.

Any help would be appreciated, thanks!

Answer

Radek Paviensky picture Radek Paviensky · Sep 30, 2010

And what about this one :-) Solutions by @shingana, @kandadaboggu will not work as there is no "super" here. You want to call original version not the super version.

module WillPaginate
  class LinkRenderer
    alias_method :to_html_original, :to_html
    def to_html
      debugger
      to_html_original
    end
  end
end