My controller has many similar codes so I want to refactor them.
respond_to do |format|
if @plan.save
format.html { redirect_to '/mypage', notice:
i18n_field(:match_exist) } ###HERE!!!!!
format.json { render json: @plan, status: :created, location:
@plan }
else
format.html { render action: "new" }
format.json { render json: @plan.errors, status:
:unprocessable_entity }
end
end
(and the same except a different symbol instead of :match_exist)
How would you refactor them ?
Make a private method that accepts the thing you want to match. (Just
like any other "extract what's common and parameterize it" sort of
refactoring. Sorry I'm not familiar with the semi-official names of
the common refactorings.) So, you'd wind up with something like:
class PlansController < ApplicationController
def one_action
save_with_varied_notice params, :match_exist
end
...
def another_action
save_with_varied_notice params, :plan_create_success
end
private
def save_with_varied_notice params, match_symbol
# insert here whatever it is you do to find or make @plan
respond_to do |format|
if @plan.save
format.html { redirect_to '/mypage',
notice: i18n_field(:match_symbol) }
format.json { render json: @plan, status: :created,
location: @plan }
else
format.html { render action: "new" }
format.json { render json: @plan.errors,
status: :unprocessable_entity }
end
end
end