从Rails插件向Rails引擎模型添加方法

我正在编写一个Rails插件来扩展Rails引擎。 即MyPluginMyEngine作为依赖项。

在我的Rails引擎上,我有一个MyEngine::Foo模型。

我想为这个模型添加新方法,所以我在我的插件app/models/my_engine/foo.rb创建了一个文件,其中包含以下代码:

 module MyEngine class Foo def sayhi puts "hi" end end end 

如果我在插件虚拟应用程序上进入Rails控制台,我可以找到MyEngine::Foo ,但运行MyEngine::Foo.new.sayhi返回

NoMethodError:未定义的方法`sayhi’

为什么MyPlugin无法看到MyEngine::Foo模型的更新? 我哪里错了?

好的,发现了。 要使MyPlugin知道并能够修改MyEngine模型,必须在插件engine.rb上使用engine.rb如下所示:

 require "MyEngine" module MyPlugin class Engine < ::Rails::Engine isolate_namespace MyPlugin # You can also inherit the ApplicationController from MyEngine config.parent_controller = 'MyEngine::ApplicationController' end end 

为了扩展MyEngine::Foo模型,我必须创建一个文件lib/my_engine/foo_extension.rb

 require 'active_support/concern' module FooExtension extend ActiveSupport::Concern def sayhi puts "Hi!" end class_methods do def sayhello puts "Hello!" end end end ::MyEngine::Foo(:include, FooExtension) 

并在config/initializers/my_engine_extensions.rb要求它

 require 'my_engine/foo_extension' 

现在从MyPlugin我可以:

  MyEngine::Foo.new.sayhi => "Hi!" MyEngine::Foo.sayhello => "Hello!" 

有关更多详细信息,请参阅ActiveSupport Concern 文档 。