覆盖 Rails Engine 控制器操作
我正在使用 Rails 引擎,但我需要自定义一些控制器操作。
我实际上分叉了引擎,并将这些自定义实现到我自己的分叉中,但我想知道 Rails Engines 中是否有官方方法来覆盖和自定义控制器。
i'm using a Rails engine, but i need to customize some controllers actions.
I actually forked the engine, and implementing those customizations into my own fork, but i was wondering if there is an official way in Rails Engines to override and customize controllers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要在自己的
app\controllers
文件夹中定义一个同名的控制器,就会首先找到它。这样您就可以轻松定制它。
请注意:因为它是最先找到的,所以您需要更换发动机上的整个控制器。这可能正是您想要的。在某些情况下,你只想稍微调整一下,那么最好重新打开类,只重新定义需要的内容。
可以在这里找到要做的示例:http://edgeguides.rubyonrails。 org/engines.html#overriding-models-and-controllers
Just define a controller with the same name in your own
app\controllers
folder, and it will be found first.That way you can easily customize it.
Please note: because it is found first, you replace the entire controller from the engine. This could be exactly what you want. In some cases, you just want to adjust a little, then it is much better to reopen the class, and only redefine what is needed.
Examples to do is can be found here: http://edgeguides.rubyonrails.org/engines.html#overriding-models-and-controllers
接受的答案中的链接实际上并未提供覆盖控制器的示例。他们提到“开放分类”文件,但没有解释具体如何做。如果您在应用程序中打开引擎类,您将收到循环依赖错误,因为您正在引用/打开当前正在定义的类。因此,您需要确保首先加载引擎的实际类。
就我而言,我使用 Blazer gem 并向其添加身份验证。由于我使用 Blazer 不直接支持的声明性授权,因此我需要打开 Blazer 的基本控制器并向其添加我的授权要求。
The link in the accepted answer does not actually provide an example to overriding a controller. They mention "open classing" the file, but don't explain how exactly to do it. If you open the engine class in your app, you will get a circular dependency error because you are referencing/opening a class that is currently in the process of being defined. Therefore, you need to make sure you load the engine's actual class first.
In my case, I'm using the Blazer gem and adding authentication to it. Since I use declarative authorization, which Blazer does not directly support, I need to open up Blazer's base controller and add my authorization requirement to it.