views:

105

answers:

2

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
+8  A: 

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/>')
jdl
Exactly what I was looking for.
Lawrence Barsanti
Happy to help out.
jdl
A: 

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 />')
klew