Lawrence Barsanti
Lawrence Barsanti

Reputation: 33222

Is there a more compact way to write this ROR code?

Is there a more compact way to write the following code. I would like to get rid of the line that assigns the empty string when flash[:add_run_error] is nil.

unless run.save 
  run.errors.each do |attr, msg|  
    flash[:add_run_error] += '<br/>' if flash[:add_run_error] 
    flash[:add_run_error] = '' unless flash[:add_run_error] 
    flash[:add_run_error] += "Invalid #{attr}.  Follow examples below." 
  end 
end

Upvotes: 1

Views: 148

Answers (2)

klew
klew

Reputation: 14967

I would do it this way:

unless run.save 
  add_run_errors = []
  run.errors.each do |attr, msg|  
    add_run_errors << "Invalid #{attr}.  Follow examples below." 
  end 
  flash[:add_run_error] = add_run_errors.join '<br />'
end

But it is without first <br /> - you can add it simply:

  flash[:add_run_error] = '<br /'> + (add_run_errors.join '<br />')

Upvotes: 0

jdl
jdl

Reputation: 17790

You could simply join the attr part of your errors together.

flash[:add_run_error] = run.errors.map{|attr, msg| "Invalid #{attr}.  Follow examples below."}.join('<br/>')

Upvotes: 8

Related Questions