且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-02 20:55:16

好的,找到了。要使 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.