问题描述
我有一个引擎,它定义了一些模型和控制器.我希望能够在我的应用程序中扩展某些模型/控制器的功能(例如添加方法),而不会失去引擎的原始模型/控制器功能.我在任何地方读到,您只需要在应用程序中定义具有相同名称的控制器,Rails 会自动合并它们,但是它对我不起作用,并且引擎中的控制器被简单地忽略(我认为它甚至没有加载).
I have an engine which defines some models and controllers. I want to be able to extend functionality of some models/controllers in my application (eg. adding methods) without loosing the original model/controller functionality from engine. Everywhere I read that you simply need to define controller with the same name in your application and Rails will automatically merge them, however it doesn't work for me and controller in engine is simply ignored (I don't think it's even loaded).
推荐答案
如果其他人在未来某个时候遇到同样的问题,这是我编写的解决我问题的代码:
Just if anyone else runs into same issue some time in the future, this is the code I wrote that fixed my problem:
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
如果文件路径以app"开头,这将在从应用程序请求之前自动从引擎请求文件.
This will automatically require files from engine before requiring from application if file path starts with 'app'.
这篇关于Rails 引擎扩展功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!