如何对现有的 gem(Rails 引擎)进行猴子补丁?
我正在开始使用 Ruby 和 Rails 3。我想使用一个 Rails 引擎(打包为 Gem),但它并不完全按照我想要的方式工作。我想做一些细微的修改,但不想创建我自己的分叉版本。我认为这就是猴子补丁发挥作用的地方。
作为 Ruby 新手(并且有 PHP 背景),猴子补丁对我来说是一个新概念。我将如何对现有的 gem 进行猴子修补,以及如何组织我的修改?我正在寻找一些“最佳实践”方法。
I'm getting started with Ruby and Rails 3. There is a Rails Engine (packaged as a Gem) that I would like to use but it doesn't work exactly as I would like it to. I want to make some slight modifications but don't want to have to create my own forked version. I think this is where monkey patching becomes useful.
Being new to Ruby (and coming from a PHP background) monkey patching is a new concept to me. How would I go about monkey patching an existing gem, and how would I go about organizing my modifications? I'm looking for some "best practice" approaches to this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个非常广泛的问题,因为您没有提到什么 gem 或您想要如何修改行为,但是......
一般来说,解决这个问题的方法(解决这个问题的一种方法)是打开 gem。使用可以打开所有文件的编辑器,以便您可以轻松地从一个文件切换到另一个文件。查看 gem 时,找出哪个类包含您想要更改的功能。
因此,您可以转到测试或规范目录并编写如下测试:
然后运行测试。当然,它们会失败,因为您的新功能没有到位。
现在,假设您的更改进入
AwesomeAuthentication
类的spit_out_error_message
中。您可以在项目中创建一个类——可能在 lib/awesome_auth.rb 或类似的地方。在其中,您按照此处所述进行操作:Rails 3:alias_method_chain 仍然使用吗?。您还需要阅读以下内容: http://yehudakatz.com/ 2009/03/06/alias_method_chain-in-models/,它描述了使用此技术修改现有类(滚动到底部)。因此,您创建一个新的
spit_out_error_message
,按照上述方式拼凑它并重新运行测试。This is a very broad question because you didn't mention what gem or how you wanted to modify the behavior, but...
In general, the way to approach this (one way to approach this) is open the gem up. Use an editor that can open all the files so you can easily flip from one to another. When looking at the gem, figure out which class contains the functionality you want to change.
So, you go to your test or spec directory and write a test like:
and run your tests. Of course they fail because your new functionality is not in place.
Now, say your change goes in
spit_out_error_message
in classAwesomeAuthentication
. You can create a class in your project -- probably in lib/awesome_auth.rb or something like that. In it, you do as described here: Rails 3: alias_method_chain still used?. You'll also want to read this: http://yehudakatz.com/2009/03/06/alias_method_chain-in-models/, as it describes modifying an existing class using this technique (scroll to the bottom).So you create a new
spit_out_error_message
, cobble it in as described above and rerun the tests.