I have some controller methods I\'d like to share. What is the best practice for doing this in ruby on rails? Should I create an abstract class that my controllers extend, o
I agree with the module approach. Create a separate Ruby file in your lib directory and put the module in the new file.
The most obvious way would be to add the methods to your ApplicationController, but I am sure you know that already.
I know this question was asked 6 years ago. Just want to point out that in Rails 4, there're now Controller Concerns that're a more out of the box solution.
I actually think a module is the best way to share code amongst controllers. Helpers are good if you want to share code amongst views. Helpers are basically glorified modules, so if you don't need view level access, I suggest placing a module in your lib folder.
Once you create the module, you'll have to use the include statement to include it in the desired controllers.
http://www.rubyist.net/~slagell/ruby/modules.html
In my opinion, normal OO design principles apply:
Maps
, and access the methods like: Maps::driving_directions
.class MapController < ApplicationController
) and put the shared code there.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:
if you want to share codes between controller and helpers, then you should try creating a module in library. You can use @template and @controller for accessing method in controller and helper as well. Check this for more details http://www.shanison.com/?p=305
Another possibility:
If your common code needs state and you want to share the behavior amongst controllers, you could put it in a plain old ruby class in either your model
or lib
directory. Remember that model
classes don't have to be persistent even though all ActiveRecord classes are persistent. In other words, it's acceptable to have transient model
classes.