猴子补丁时将代码放在哪里 [英] Where to put code when monkey patching

查看:54
本文介绍了猴子补丁时将代码放在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读到的关于猴子补丁的所有内容都说要做这样的事情:

Everything I read about monkey patching says to do something like this:

class String
  def foo
    #your special code 
  end
end

但是我找不到任何有关将此代码放在哪里的说明.在 Rails 应用程序中,我可以把它放在任何我想要的疯狂地方吗?在一个模块中?一个模型?

But I can't find any instructions on where to put this code. In a rails app, can I just put this any crazy place I want? In a Module? A Model?

我是否需要在定义我的monkeypatch 的文件中包含某些内容?我是否需要在我想要使用的任何地方都包含我的monkeypatch?

Do I need to include something in the file where I define my monkeypatch? Do I need to include my monkeypatch everywhere where I want to use it?

推荐答案

对此没有固定规则.从技术上讲,您可以在任何地方打开它(类;并添加您的方法).我通常会制作一个名为 monkey_patches.rb 的特殊文件,并将它放在我的 Rails 应用程序的 config/initializersmisc 文件夹中,如果有的话我知道去哪里寻找冲突.

There is no set rule on this. Technically you can open it (the class; and add your method) anywhere. I usually make a special file called monkey_patches.rb and put it in config/initializers or in a misc folder in my Rails app so if theres ever a conflict I know where to look.

另外我建议使用 Module 来包装猴子补丁.查看 3 种无需猴子补丁的方法弄乱以获取更多信息.

Also I'd advise to use a Module to wrap the monkey patch. Check out 3 ways to monkey patch without making a mess for more info.

他的例子:

module CoreExtensions
  module DateTime
    module BusinessDays
      def weekday?
        !sunday? && !saturday?
      end
    end
  end
end

DateTime.include CoreExtensions::DateTime::BusinessDays

这篇关于猴子补丁时将代码放在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆