猴子修补时放置代码的位置

Lif*_*nts 7 ruby monkeypatching ruby-on-rails

我读到的关于猴子修补的一切都说要做这样的事情:

class String
  def foo
    #your special code 
  end
end
Run Code Online (Sandbox Code Playgroud)

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

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

vir*_*xru 12

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

另外我建议使用a Module来包裹猴子补丁.查看3种方法来修补猴子而不会弄得一团糟以获取更多信息.

他的榜样:

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

DateTime.include CoreExtensions::DateTime::BusinessDays
Run Code Online (Sandbox Code Playgroud)

  • 我确实尝试将 `config/initializers` 中的文件命名为有意义的东西,比如在这种情况下是 `business_days.rb`,而不是像 `monkey_patches.rb` 或 `embarrassing_collection_of_unfortunate_hacks.rb` 这样容易混淆的通用名称。如果您有一个允许按名称快速打开的编辑器,如果您必须在名称一致的情况下进行调整,则很容易将其拉出。 (2认同)

Epi*_*ene 5

我使用了 Justin Weiss 在3 Ways to Monkey-Patch Without Making a Mess中描述的以下技术

例如,在普通 Ruby(例如 gem)中,您可以在所需的某个文件中定义一个模块,然后include(或extend将该模块放入所需的类中。

module StringMonkeypatch
  def foo
    #your special code 
  end
end

String.include StringMonkeypatch
Run Code Online (Sandbox Code Playgroud)

在 Rails 中,您可能希望在自动加载(查找autoload_paths)的位置并以遵循 Rails 命名约定的方式定义模块。

例如,如果对Sidekiq::Testinggem 类进行猴子修补,您应该镜像文件结构。

# in /app/<something telling>/sidekiq/testing/monkeypatch.rb
module Sidekiq::Testing::Monkeypatch
  def foo
    #your special code 
  end
end

# in /config/environment.rb, at the bootom
Sidekiq::Testing.include Sidekiq::Testing::Monkeypatch
Run Code Online (Sandbox Code Playgroud)