我有一个定义了一些模型和控制器的引擎。我希望能够在应用程序中扩展某些模型/控制器的功能(例如,添加方法),而不会丢失引擎的原始模型/控制器功能。在我读到的任何地方,你只需要在你的应用程序中定义具有相同名称的控制器,Rails会自动合并它们,但是这对我来说不起作用,engine中的控制器被简单地忽略了(我认为它甚至都没有加载)。
发布于 2010-06-07 22:53:48
如果将来其他人遇到同样的问题,这是我写的代码,解决了我的问题:
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”开头,这将在从应用程序请求文件之前自动要求引擎提供文件。
发布于 2011-03-15 15:51:14
require MyEngine::Engine.root.join('app', 'models', 'my_engine', 'my_model')在应用程序中的模型类定义之前。
发布于 2011-02-24 04:43:14
您可以将以下行添加到lib根目录下的引擎模块文件中:
def self.root
File.expand_path(File.dirname(File.dirname(__FILE__)))
end
def self.models_dir
"#{root}/app/models"
end
def self.controllers_dir
"#{root}/app/controllers"
end然后,您可以在主应用程序(利用引擎的应用程序)中从引擎请求必要的文件。这很好,因为您维护了Rails引擎的默认功能,并且有一个简单的工具来使用普通的ruby继承,而不需要打补丁。
例如:
#ENGINE Model -
class User < ActiveRecord::Base
def testing_engine
puts "Engine Method"
end
end
#MAIN APP Model -
require "#{MyEngine.models_dir}/user"
class User
def testing_main_app
puts "Main App Method"
end
end
#From the Main apps console
user = User.new
puts user.testing_engine #=> "Engine Method"
puts user.tesing_main_app #=> "Main App Method"https://stackoverflow.com/questions/2964050
复制相似问题