It depends how much coding is shared and how widely you want to make it available. There are two DRY options:
- Put the shared code into an application method (in application.rb) and then accesses it by calling the method from within each of the controller methods that need to run that code
- Create a module that contains methods that incorporate the required code and then mixin the code in the controllers where it is required.
If the code is relatively small and needed across many of your controllers, then option 1 is usually best. If the code is relatively large and used by only a small number of controller, then option 2 is probably better. Between these two extremes, it's a case of personal choice as to which to use.
consider these two methods:
a. A method added to application.rb
b. A module created as /lib/subtraction_stuff.rb
def add_a_to_b(a, b)
a + b
To use the method add_a_to_b within a controller, you'd simply add:
def subtract_a_from_b(a, b)
a - b
To use the method subtract_a_from_b you need to do this:
@result = add_a_to_b(1,5)
That is to mixin the module using an include statement, and then use the method within a controller method.
class SomeController < ApplicationController
@result = subtract_a_from_b(40, 10)