Reputation: 1
I have two controllers having update action. Both the action have similar code and I am in a confusion how to remove duplication and make it dry. Code climate showing duplication problem in this one. Here are the details.
Controller 1: respond_to do |format| if @business_profile.update(business_profiles_params) format.html { redirect_to settings_path, notice: t('setting_successful_message') } else format.html { redirect_to settings_path, alert: t('setting_failure_message') end end
Controller 2: respond_to do |format| if @contact.update(contact_params) format.html { redirect_to contacts_path, notice: t('contact_successful_message') } else format.html { redirect_to contacts_path, alert: t('contact_failure_message') end end
so I want this similar content to be in one.
Upvotes: 0
Views: 1072
Reputation: 88
They are both missing end
s to the if
block and the first one probably has a typo in stting_failure_message
. Both have missing curly right braces (}
) in the else
block. There may be more subtle issues.
Get the code running and passing controller tests before worrying about optimizations like extracting a shared method to call from the two controller update methods. For what it's worth, the current degree of duplication looks about right to me, in the local clarity of expression and independence in changes versus abstraction to de-duplicate code trade off. Look at this questions for a more general discussion of best practices in DRYing up controllers: Best Practices for reusing code between controllers in Ruby on Rails
and the highest rated answer in this one re the cost/benefit of the extraction you are considering
Upvotes: 1
Reputation: 7167
Checkout the responders gem, specifically FlashResponder (https://github.com/plataformatec/responders#flashresponder) and CollectionResponder (https://github.com/plataformatec/responders#collectionresponder) if you plan to respond with flash messages and redirect to the index action often.
Upvotes: 0