Refactor respond_to block

Rails 3.1.3

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


respond_to do |format|
if @plan.save
format.html { redirect_to ‘/mypage’, notice:
i18n_field(:plan_create_success) } ###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

The only difference is “i18n_field(… )” parts as you can see.

How would you refactor them ?

Thanks!

soichi

On Sun, Nov 25, 2012 at 8:19 PM, Soichi I. [email protected]
wrote:

      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 A., 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/.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs