如何在Ruby on Rails中修补补丁?

jay*_*ode 6 monkeypatching ruby-on-rails

让我们使用一个真实世界的例子.

我想修补一下WillPaginate :: LinkRenderer.to_html方法.

到目前为止,我尝试过:

  1. 在文件夹中创建了一个文件:lib/monkeys/will_paginate_nohtml.rb
  2. 在config/environments.rb中添加:在文件末尾需要'monkeys/will_paginate_nohtml'
  3. 在该文件中,这是我的代码:

Ë

module Monkeys::WillPaginateNohtml
  def to_html
    debugger
    super
  end
end

WillPaginate::LinkRenderer.send(:include, Monkeys::WillPaginateNohtml)
Run Code Online (Sandbox Code Playgroud)

但不知何故,调试器无法通过.看起来修补失败了.

任何帮助将不胜感激,谢谢!

Rad*_*sky 10

那个怎么样:-) @ shingana的解决方案,@ kandadaboggu不会起作用,因为这里没有"超级".您想要调用原始版本而不是超级版本.

module WillPaginate
  class LinkRenderer
    alias_method :to_html_original, :to_html
    def to_html
      debugger
      to_html_original
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


vis*_*ise 5

你的问题的标题是误导性的.坦率地说,我觉得你可能只是想定制will_paginate页表结构,它可以以不同的方式进行.

因此,在您的情况下,正确的方法是扩展渲染器.例如,从初始化程序(通过config/initializers)加载以下内容:

class CustomPaginationRenderer < WillPaginate::LinkRenderer

  def to_html
    # Your custom code, debugger etc
  end

end
Run Code Online (Sandbox Code Playgroud)

然后,要让您的应用程序使用此渲染器,请将以下内容添加到config/environment.rb文件中:

WillPaginate::ViewHelpers.pagination_options[:renderer] = 'CustomPaginationRenderer'
Run Code Online (Sandbox Code Playgroud)