18

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.

Marco Borromeo
  • 233
  • 3
  • 7
  • Have a look there http://stackoverflow.com/questions/5045068/extending-controllers-of-a-rails-3-engine-in-the-main-app – Andrei Feb 19 '11 at 14:36

2 Answers2

21

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

nathanvda
  • 48,109
  • 12
  • 108
  • 136
13

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.

Peter P.
  • 2,718
  • 2
  • 17
  • 25
  • 1
    This should be the accepted answer since it gives an example of what the OP was asking for as well uses format the docs in the rails guide suggest. – dft Oct 25 '17 at 20:18
  • Works! Is this the most idiomatically rails way to do this? – David T Nov 02 '18 at 18:57
  • @DavidT I believe so. I see this all over in gems that produce engines. – Peter P. Nov 03 '18 at 00:39