开发者

Override a Rails Engine controller action

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 Rai开发者_如何转开发ls Engines to override and customize 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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜