我有一个定义一些模型和控制器的引擎.我希望能够在我的应用程序中扩展某些模型/控制器的功能(例如添加方法),而不会丢失引擎中的原始模型/控制器功能.在我读到的任何地方,您只需要在应用程序中定义具有相同名称的控制器,Rails将自动合并它们,但它对我不起作用,引擎中的控制器被简单地忽略(我不认为它甚至被加载).
我在我的应用程序中使用Rails引擎作为gem.引擎有PostsController很多方法,我想在我的主应用程序中扩展控制器逻辑,例如添加一些方法.如果我只是PostsController在主应用程序中创建,则不会加载引擎的控制器.
有一个解决方案提出了Rails引擎基于改变扩展功能ActiveSupport::Dependencies#require_or_load
这是唯一/正确的方法吗?如果是的话,我在哪里放这段代码?
EDIT1:
module ActiveSupport::Dependencies
alias_method :require_or_load_without_multiple, :require_or_load
def require_or_load(file_name, const_path = nil)
if file_name.starts_with?(RAILS_ROOT + '/app')
relative_name = file_name.gsub(RAILS_ROOT, '')
@engine_paths ||= Rails::Initializer.new(Rails.configuration).plugin_loader.engines.collect {|plugin| plugin.directory }
@engine_paths.each do |path|
engine_file = File.join(path, relative_name)
require_or_load_without_multiple(engine_file, const_path) if File.file?(engine_file)
end
end
require_or_load_without_multiple(file_name, const_path)
end
end
Run Code Online (Sandbox Code Playgroud)