How to Monkey Patch in Ruby on Rails?

An example of the real world is used.

I want to install the WillPaginate :: LinkRenderer.to_html monkey patch.

So far I have tried:

  • Created a file in the folder: lib / monkeys / will_paginate_nohtml.rb
  • Added in config / environment.rb: requires "monkeys / will_paginate_nohtml" at the end of the file
  • Inside this file, it was my code:

e

module Monkeys::WillPaginateNohtml def to_html debugger super end end WillPaginate::LinkRenderer.send(:include, Monkeys::WillPaginateNohtml) 

But somehow the debugger does not go through. It looks like the fix failed.

Any help would be appreciated, thanks!

+6
ruby-on-rails monkeypatching
source share
4 answers

What about this :-) The solutions from @shingana, @kandadaboggu will not work, since there is no β€œsuper” here. You want to call the 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 
+10
source share

The name of your question is incorrect. Honestly, I think you probably just want to set up the will_paginate page list structure, which can be done in different ways.

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

 class CustomPaginationRenderer < WillPaginate::LinkRenderer def to_html # Your custom code, debugger etc end end 

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

 WillPaginate::ViewHelpers.pagination_options[:renderer] = 'CustomPaginationRenderer' 
+5
source share

I think you need to open a method

 module WillPaginate class LinkRenderer def to_html debugger super end end end 
0
source share

Try the following:

 class WillPaginate::LinkRenderer def to_html debugger super end end 
0
source share

All Articles