jos*_*arh 6 ruby-on-rails rails-engines
我有一个引擎,它在其初始化器中扩展另一个引擎类,如下所示:
module MyApp
class Engine < ::Rails::Engine
initializer 'extend Product' do
AnotherApp::Product.send :include, MyApp::ProductExtender
end
end
end
Run Code Online (Sandbox Code Playgroud)
该ProductExtender
模块在包含它时调用AnotherApp :: Product上的一些方法,例如
module ProductExtender
def self.included( model )
model.send :include, MethodsToCall
end
module MethodsToCall
def self.included( m )
m.has_many :variations
end
end
end
Run Code Online (Sandbox Code Playgroud)
这适用于测试和生产环境,但是当我尝试调用ProductExtender定义的东西时config.cache_classes = false
,它会抛出一个对象NoMethodError
,比如@ product.variations.
毋庸置疑,看到我的所有测试都通过,然后在开发过程中遇到错误,这是令人不寒而栗的.当我设置时它不会发生cache_classes = true
,但它让我想知道我是否正在做一些我不应该做的事情.
我的问题有两个:为什么会发生这种情况,是否有更好的方法来实现在另一个应用程序对象上扩展/调用方法的功能?
谢谢大家!
to_prepare
我设法使用块而不是初始化器来解决这个问题。该to_prepare
块在生产中和开发中的每个请求之前执行一次,因此似乎满足我们的需求。
我在研究时并不明显,Rails::Engine
因为它是继承自Rails::Railtie::Configuration
.
因此,我不会使用问题中的代码,而是:
module MyApp
class Engine < ::Rails::Engine
config.to_prepare do
AnotherApp::Product.send :include, MyApp::ProductExtender
end
end
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1364 次 |
最近记录: |