Rails 引擎扩展功能
我有一个定义一些模型和控制器的引擎。我希望能够扩展应用程序中某些模型/控制器的功能(例如添加方法),而不会丢失引擎的原始模型/控制器功能。我到处都读到,你只需要在应用程序中定义具有相同名称的控制器,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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在应用程序中的模型类定义之前。
before the model class definition in your application.
您可以将这些行添加到 lib 根目录中的引擎模块文件中:
然后您可以在主应用程序(使用引擎的应用程序)中从引擎请求必要的文件。这很好,因为您可以维护 Rails Engines 的默认功能,并且还拥有一个简单的工具来使用正常的 ruby 继承,而无需修补。
前任:
You can add these lines to you engine's module file in the lib root directory:
Then you have the ability in the main application (the app making use of the engine) to require the necessary files from the engine. This is nice because you maintain Rails Engines default functionality and also have an easy tool for making use of normal ruby inheritance, without the need for patching.
EX:
如果其他人将来某个时候遇到同样的问题,这就是我编写的解决问题的代码:
如果文件路径以“app”开头,这将在从应用程序请求之前自动从引擎请求文件。
Just if anyone else runs into same issue some time in the future, this is the code I wrote that fixed my problem:
This will automatically require files from engine before requiring from application if file path starts with 'app'.
确实如此。将使用最先找到的控制器。
因此,要使其正常工作,您可能有两个选择:
据我所知,由于没有多重继承,所以这是唯一的方法。
希望这有帮助。
That is true. The controller that is found first will be used.
So to make it work you might have two options:
According to me, since there is no multiple inheritance, that is the only way.
Hope this helps.
您可以更改引擎的加载顺序,以避免每个型号的要求。
在 config/application.rb 中添加以下行:
这将确保 MyEngine 中的模型在 MyApp 之前加载
You can change the load order of the engine to avoid the require on each of your models.
In config/application.rb add this line:
This will ensure that the models from MyEngine are loaded before MyApp
我以前从未使用过引擎,但是你不能定义一个继承自引擎提供的控制器的新控制器吗
I've never used Engines before but can't you define a new controller that inherits from the controller provided by the engine