如何在 Ruby on Rails 中进行猴子补丁?
让我们使用一个现实世界的例子。
我想猴子修补 WillPaginate::LinkRenderer.to_html 方法。
到目前为止,我已经尝试过:
- 在文件夹中创建了一个文件:lib/monkeys/will_paginate_nohtml.rb
- 在 config/environments.rb 中添加:在文件末尾需要 'monkeys/will_paginate_nohtml'
- 在该文件内,这是我的代码:
e
module Monkeys::WillPaginateNohtml
def to_html
debugger
super
end
end
WillPaginate::LinkRenderer.send(:include, Monkeys::WillPaginateNohtml)
但是不知何故,调试器没有通过。看起来补丁失败了。
任何帮助将不胜感激,谢谢!
Lets use a real world example.
I want to monkey patch WillPaginate::LinkRenderer.to_html method.
So far I have tried:
- Created a file in folder: lib/monkeys/will_paginate_nohtml.rb
- Added in config/environments.rb: require 'monkeys/will_paginate_nohtml' at the end of the file
- 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那么这个呢:-) @shingana、@kandadaboggu 的解决方案将不起作用,因为这里没有“超级”。您想要调用原始版本而不是超级版本。
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.
你的问题的标题具有误导性。坦率地说,我认为您可能只是想自定义 will_paginate 页面列表结构,这可以以不同的方式完成。
因此,在您的情况下,正确的方法是扩展渲染器。例如,从初始化程序加载以下内容(通过 config/initializers):
然后,要让您的应用程序使用此渲染器,请将以下内容添加到您的 config/environment.rb 文件中:
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):
Then, to have your application use this renderer add the following to your config/environment.rb file:
我认为你需要打开该方法
I think you need open the method
试试这个:
Try this: