Ruby on Rails

So last week while I was programming for a project and I came across a need for having the same code in 2 controllers. If you’re unfamiliar with the programming practices especially in Ruby on Rails, you may not know this. Code repetition is really frowned up on in most of the programing languages. You shouldn’t be writing the same code over and over again. That got me thinking and I found that Rails has concerns which is something I am supposed to use for sharing code. So let me explain how this is done.

We will group together all our shared code in methods and add those to concerns. Then these concerns will be included in all the controllers where you need access to these code/methods. By doing this you will be able to call these methods from the controllers.

See the example below to understand more on this.

# app/controllers/concerns/your_controller_concern.rb

module YourControllerConcern
 extend ActiveSupport::Concern 
 included do 
  helper_method :method3
 end 
 def method3
  # method code here
 end 
end

Now include this concern in your controllers where you would need to access the method method3:

class CartsController < ApplicationController
 include YourControllerConcern 
 # rest of the controller codes 
end 

class OrdersController < ApplicationController 
 include YourControllerConcern 
 # rest of the controller codes 
end

Now, you should be able to use method3 in both controllers.

More info