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</p>
<p>module YourControllerConcern<br />
 extend ActiveSupport::Concern<br />
 included do<br />
  helper_method :method3<br />
 end<br />
 def method3<br />
  # method code here<br />
 end<br />
end

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

<br />
class CartsController &lt; ApplicationController<br />
 include YourControllerConcern<br />
 # rest of the controller codes<br />
end </p>
<p>class OrdersController &lt; ApplicationController<br />
 include YourControllerConcern<br />
 # rest of the controller codes<br />
end<br />

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

More info