DRY controllers in Rails 3.2

After analyzing the climate, I found that my controllers are not as dry as they could be. Methods like:

def index @animals = current_user.animals.valid_animals.search(params[:search], params[:page]) respond_to do |format| format.html # index.html.erb format.json { render json: @animals } end end 

Basically equal in all controllers.

In principle, the generated relay rails code is "the same" in all controllers. How can I make it cleaner and drier in real good shape?

early

+8
ruby ruby-on-rails-3 dry
source share
3 answers

You can use reply_with for these actions.

 class AnimalController < ApplicationController respond_to :html, :json def index @animals = current_user.animals.valid_animals.search(params[:search], params[:page]) respond_with @animals end end 
+3
source share

There is no need to make the DRY code as you stated. Think about it, one of the main goals of creating your DRY code is that if you update the code in one place, you won’t have to update the code in another place. However, in your case, if you update your code in controller X, what are the chances that you will make the same change in controller Y? If not, then this is not a good candidate for abstraction. (In fact, if you are even going to remotely change something in X that does not affect Y, then this is a bad candidate for DRY)

As a rule, abstraction is good. However, excessive abstraction is not very good and should be avoided.

+10
source share

Ken Lee is right, this is not very good over abstraction, and in this case is a little unnecessary, although if you have repeated code in your controllers, you can use the Before, Around, and After Filters to dry the code.

+2
source share

All Articles