10

I have a piece of code that is needed in 2 of my controllers, but not all of them. Where does this method belong? I have read about helpers, but those seem to be for view-related code. Someone proposed the lib-folder, but that seems 'too far away' from the controller logic, i don't need it in views or models. Has someone experience with that sort of problem?

1 Answer 1

12

There are three options, the easiest (though, the most unclean) is the application controller. The other two options are a shared parent controller

class FooController < FooBarParentController
   # code here  
end

class BarController < FooBarParentController
   # code here  
end

Usage depends on how related these controllers are.

The final solution is a module

module FooBarModule
  extend ActiveSupport::Concern

  included do
    # class level code
    # before_filter ....
  end

  module ClassMethods
    # all class methods here
  end

  # instance methods here
end

This is where the shared code required is for a handful of ad-hoc controllers, or if you are already using the inheritance above and this code doesn't quite fit into this subset (thus attempting to emulate multiple inheritance).

Sign up to request clarification or add additional context in comments.

4 Comments

thanks for this helpful answer! the last solution seems to me the most flexible, so i think i will try this one. could you explain a little where i should put this code (in a module in the lib-folder?)
I'd personally put it in the controllers folder.
If it pertains specifically to this application, put it under the app folder (perhaps in a 'modules' subdirectory). The lib folder is more for general purpose utilities that aren't app specific.
thanks very much, that really helped me. i ended up putting the file with the FooBarModule in the controllers-folder, because as i said it is only controller-related. i could then just 'include FooBarModule' in my controllers (i didn't even need to require it first, as i had thought). Works like a charm!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.