On Sun, Nov 25, 2012 at 8:19 PM, Soichi Ishida
<lists-fsXkhYbjdPsEEoCn2XhGlw@public.gmane.org> wrote:
> 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
end
Nice and DRY now. Did you see what I did there?
-Dave
--
Dave Aronson, the T. Rex of Codosaurus LLC,
secret-cleared freelance software developer
taking contracts in or near NoVa or remote.
See information at http://www.Codosaur.us/.
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
For more options, visit https://groups.google.com/groups/opt_out.