如何修补在 Rails 中自动加载的代码? [英] How to monkey-patch code that gets auto-loaded in Rails?
问题描述
我正在使用以下内容修补 Rails 引擎:
I'm monkey-patching a Rails engine with something like:
SomeClass.class_eval do
# ...
end
我第一次访问网站时,至少在开发模式下,它可以工作,但第二次就好像我的补丁从未存在过一样.我认为它是 Rails 自动重新加载引擎(安装在 vendor/中)而不是重新加载我的代码.这是 Rails 2.3.
The first time I hit the web site, on development mode at least, it works, but the second time it's like my patch never existed. I presume it's Rails auto-reloading the engine (which is installed in vendor/) and not reloading my code. This is Rails 2.3.
有什么想法可以让我的代码也重新加载吗?
Any ideas how to do it so that my code also gets reloaded?
推荐答案
此解决方案仅适用于 Rails 3+,因为它依赖于 Rails::Railtie 中的某些功能.将此代码放在初始化程序中.
This solution only works for Rails 3+ since it's dependent on some functionality in Rails::Railtie. Put this code in an initializer.
这个问题很老了,但我找到了一个解决方案:
This question is quite old, but here's a solution I found:
Rails.configuration.to_prepare do
SomeClass.class_eval do
# ...
end
end
这会强制 Rails 在开发模式下对每个请求重新加载类,但在生产模式中只加载一次.
This forces Rails to reload the class on every request in development mode, but only once in production.
这篇关于如何修补在 Rails 中自动加载的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!