Dipak Panchal
Dipak Panchal

Reputation: 6036

How to dry duplicate code in controller

Status Controller

respond_to do |format|
   format.html
   format.js
   if @status.present? && @status.valid?
      format.json { render json: @status.to_json }
   else
      format.json { render json: @status.errors.values.join(",") }
   end     

Another Controller have same above code just change @status.

I am using Code Climate in that I am getting duplication of code warning.

So how to optimize that code?

Thanks In Advance

Upvotes: 0

Views: 498

Answers (2)

agios
agios

Reputation: 526

You could add a method in a parent controller (or ApplicationController) such as:

def render_valid_resource format, resource
  if resource.present? && resource.valid?
    format.json { render json: resource.to_json }
  else
    format.json { render json: resource.errors.values.join(",") }
  end
end

and then just call render_valid_resource format, @status

As an aside, if you find yourself with many more similar cases, you could look into a more structured approach using a gem such as https://github.com/plataformatec/responders

Upvotes: 2

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16507

For example as follows:

json =
if @status.present? && @status.valid?
   @status.to_json
else
   @status.errors.values.join(",")
end
format.json { render json: json }

or in the single line:

json = @status.present? && @status.valid? && @status.to_json || @status.errors.values.join(",")
format.json { render json: json }

Upvotes: 1

Related Questions