Search code examples
ruby-on-railsroutescontrollers

Middle man controller for Rails


I have two application controllers for my app. One that holds all my internal information and checks to see if users are logged in. The other application controller is under a namespace called external. This controller allows users to go to certain urls with a token, and the token represents a company that gets validated to see if the token belongs to a company. This way a user doesn't need to be logged it, they just need to know their uniq token.

The problem that I am facing is that there are autocomplete methods that I want to reuse that belong to my main application controller, but this controller checks to see if users are logged in so I get a 401 if I try to search on the external side.

I know there is no double inheritance in rails, but is there a way to kind of get a controller to belong to two different controllers? That way I can stick all my auto complete methods in this controller and both my Application controllers will be able to have access to it.

The main reason why I want to keep the auto complete methods in a controllers is so that I can make routes to them and have the actions return JSON so that JQuery autocomplete can use this information.

Thank you guys in advance, and if I am thinking about this wrong, please let me know and any other ideas you may have to accomplish this.


Solution

  • You can accomplish this by creating a module with your auto complete methods (and whatever other methods you want to share between controllers) and include the module in the appropriate controllers.

    module ModuleName
      def some_method
        ...
      end
      ...
    end
    

    in the controller:

    class ControllerName < ApplicationController
      include ModuleName
      ...
    end
    

    some_method will be available in ControllerName and any other controller that includes the module