Best Practices for reusing code between controllers in Ruby on Rails

In my opinion, normal OO design principles apply:

  • If the code is really a set of utilities that doesn’t need access to object state, I would consider putting it in a module to be called separately. For instance, if the code is all mapping utilities, create a module Maps, and access the methods like: Maps::driving_directions.
  • If the code needs state and is used or could be used in every controller, put the code in ApplicationController.
  • If the code needs state and is used in a subset of all controllers that are closely and logically related (i.e. all about maps) then create a base class (class MapController < ApplicationController) and put the shared code there.
  • If the code needs state and is used in a subset of all controllers that are not very closely related, put it in a module and include it in necessary controllers.

In your case, the methods need state (params), so the choice depends on the logical relationship between the controllers that need it.
In addition:

Also:

  • Use partials when possible for repeated code and either place in a common ‘partials’ directory or include via a specific path.
  • Stick to a RESTful approach when possible (for methods) and if you find yourself creating a lot of non-RESTful methods consider extracting them to their own controller.

Leave a Comment