简体   繁体   English

猴子修补在Rails 3

[英]Monkey Patching in Rails 3

What is the preferred way to Monkey Patch in Rails 3? 在Rails 3中使用Monkey Patch的首选方法是什么?

I just want to add a method to the String class. 我只想在String类中添加一个方法。 I'm more looking at where to place the file. 我更关注文件的放置位置。

The initializer directory is a good place to collect all those little scraps. 初始化程序目录是收集所有这些小碎片的好地方。 Since I tend to go a bit overboard with core extensions, I like to make a folder there called "extensions" and toss them all in there. 由于我倾向于对核心扩展有点过分,我喜欢创建一个名为“扩展”的文件夹并将它们全部丢弃。

So, try /config/initializers/string_extension.rb , or /config/initializers/extensions/string.rb , or something similar. 因此,请尝试/config/initializers/string_extension.rb/config/initializers/extensions/string.rb或类似的东西。 Either way, you can just forget about them afterward - Rails will require them for you, so you don't need to do it yourself. 无论哪种方式,你可以在以后忘记它们--Rails会为你要求它们,所以你不需要自己动手。

If it is class specific you could just re-define the method in the class you need it for. 如果它是特定于类的,您可以在您需要的类中重新定义该方法。 Otherwise, it totally depends on which part of the app you want to use your string method. 否则,它完全取决于您要使用字符串方法的应用程序的哪个部分。 As an example of opening a class to redefine a method: http://codepad.org/Cj1LHmQj but, you probably already knew you could do that. 作为打开一个类重新定义一个方法的例子: http//codepad.org/Cj1LHmQj但是,你可能已经知道你可以做到这一点。

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

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