从Rails插件向Rails引擎模型添加方法 [英] Add methods to a Rails engine model from a Rails plugin
问题描述
我正在编写一个Rails插件来扩展Rails引擎。即 MyPlugin
具有 MyEngine
作为依赖项。
I'm writing a Rails plugin to extend a Rails engine. Namely MyPlugin
has MyEngine
as a dependency.
开我的Rails引擎我有一个 MyEngine :: Foo
模型。
On my Rails engine I have a MyEngine::Foo
model.
我想为这个模型添加新的方法,所以我在我的插件 app / models / my_engine / foo.rb
其中包含以下代码:
I'd like to add new methods to this model so I created a file in my plugin app/models/my_engine/foo.rb
which has the following code:
module MyEngine
class Foo
def sayhi
puts "hi"
end
end
end
如果我在插件虚拟应用程序中输入Rails控制台,可以找到 MyEngine :: Foo
,但runnning MyEngine :: Foo.new.sayhi
返回
If I enter the Rails console on the plugin dummy application I can find MyEngine::Foo
, but runnning MyEngine::Foo.new.sayhi
returns
NoMethodError:undefined方法`sayhi'
NoMethodError: undefined method `sayhi'
为什么 MyPlugin
无法看到<$ c $的更新c> MyEngine :: Foo 模型?我在哪里错了?
Why MyPlugin
cannot see the updates to MyEngine::Foo
model? Where am I wrong?
推荐答案
好的,找到了。要使 MyPlugin
知道并且能够修改 MyEngine
模型,必须在插件 engine.rb
就像这样:
Ok, found out. To make MyPlugin
aware and able to modify MyEngine
models the engine must be required on the plugin engine.rb
like so:
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
model然后我必须创建一个文件 lib / my_engine / foo_extension.rb
:
In order to extend MyEngine::Foo
model I then had to create a file 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
我可以:
Now from MyPlugin
I can:
MyEngine::Foo.new.sayhi
=> "Hi!"
MyEngine::Foo.sayhello
=> "Hello!"
请参阅 ActiveSupport Concern 文档了解更多详情。
See ActiveSupport Concern documentation for more details.
这篇关于从Rails插件向Rails引擎模型添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!