views:

50

answers:

4

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!

A: 

I think you need open the method

module WillPaginate
  class LinkRenderer
    def to_html
      debugger
      super
    end
  end
end
shingara
A: 

Try this:

class WillPaginate::LinkRenderer
  def to_html
    debugger
    super
  end
end
KandadaBoggu
+4  A: 

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
pawien
+1 because there's no "super" when you patch, although I'd prefer the answer of @vise to customize the renderer (and there'll be a "super").
hurikhan77
I already kind of miss alias_method_chain, and its only been gone for about a month
Matt Briggs
+3  A: 

The title of your question is misleading. Frankly, I think you probably just want to customize the will_paginate page list structure, which can be done differently.

So in your case the right way is to extend the renderer. For example load the following from an initializer (via config/initializers):

class CustomPaginationRenderer < WillPaginate::LinkRenderer

  def to_html
    # Your custom code, debugger etc
  end

end

Then, to have your application use this renderer add the following to your config/environment.rb file:

WillPaginate::ViewHelpers.pagination_options[:renderer] = 'CustomPaginationRenderer'
vise