简体   繁体   English

如何在 Ruby on Rails 中进行猴子补丁?

[英]How to Monkey Patch in Ruby on Rails?

Lets use a real world example.让我们使用一个真实世界的例子。

I want to monkey patch WillPaginate::LinkRenderer.to_html method.我想修补 WillPaginate::LinkRenderer.to_html 方法。

So far I have tried:到目前为止,我已经尝试过:

  1. Created a file in folder: lib/monkeys/will_paginate_nohtml.rb在文件夹中创建了一个文件:lib/monkeys/will_paginate_nohtml.rb
  2. Added in config/environments.rb: require 'monkeys/will_paginate_nohtml' at the end of the file在 config/environments.rb 中添加:文件末尾需要 'monkeys/will_paginate_nohtml'
  3. Inside that file, this was my code:在该文件中,这是我的代码:

e 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!任何帮助将不胜感激,谢谢!

And what about this one :-) Solutions by @shingana, @kandadaboggu will not work as there is no "super" here.那么这个呢 :-) @shingana,@kandadaboggu 的解决方案将不起作用,因为这里没有“超级”。 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

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.坦率地说,我认为您可能只是想自定义 will_paginate 页面列表结构,可以以不同的方式完成。

So in your case the right way is to extend the renderer.因此,在您的情况下,正确的方法是扩展渲染器。 For example load the following from an initializer (via config/initializers):例如,从初始化程序加载以下内容(通过 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:然后,要让您的应用程序使用此渲染器,请将以下内容添加到您的 config/environment.rb 文件中:

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

I think you need open the method我认为你需要打开方法

module WillPaginate
  class LinkRenderer
    def to_html
      debugger
      super
    end
  end
end

Try this:尝试这个:

module LinkRendererWrapper
  def to_html
    debugger
    super
  end
end

WillPaginate::LinkRenderer.prepend(LinkRendererWrapper)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM