覆盖 Rails Engine 控制器操作

发布于 2024-09-02 02:09:55 字数 113 浏览 3 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

涫野音 2024-09-09 02:09:55

只要在自己的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

木森分化 2024-09-09 02:09:55

接受的答案中的链接实际上并未提供覆盖控制器的示例。他们提到“开放分类”文件,但没有解释具体如何做。如果您在应用程序中打开引擎类,您将收到循环依赖错误,因为您正在引用/打开当前正在定义的类。因此,您需要确保首先加载引擎的实际类。

# in my app
# app/controllers/blazer/base_controller.rb
load Blazer::Engine.root.join('app/controllers/blazer/base_controller.rb')
Blazer::BaseController.class_eval do
  filter_access_to :all
end  

就我而言,我使用 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 app
# app/controllers/blazer/base_controller.rb
load Blazer::Engine.root.join('app/controllers/blazer/base_controller.rb')
Blazer::BaseController.class_eval do
  filter_access_to :all
end  

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文