问题
Following code climate analysis, I found that my controllers are not DRY as it could be. The 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
Are basically equal in all the controllers.
Basically, the scaffold rails generated code are "the same" in all controllers. How can I made it more clean and dry in a real good way?
thanks in advance
回答1:
You could use respond_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
回答2:
There is no need to make the code DRY in the way you stated. Think about it, one of the primary purpose of making your code DRY 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 you are going to make the same change in Controller Y? If no, then it's not a good candidate for abstraction. (In fact if you are even going to remotely change something in X which will not affect Y, then it's a bad candidate for DRY-ness)
Generally, abstraction is good. However, over-abstraction is not a good thing, and it should be avoided.
回答3:
Ken Li is right, over abstraction is not a good thing and in this case a little unnecessary, though if you do have repeated code in your controllers you can use the Before, Around and After filters to DRY out the code.
来源:https://stackoverflow.com/questions/12830558/dry-controllers-in-rails-3-2