开发者

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

开发者 https://www.devze.com 2022-12-19 18:58 出处:网络
Is there a more compact way to write the f开发者_Python百科ollowing code.I would like to get rid of the line that assigns the empty string when flash[:add_run_error] is nil.

Is there a more compact way to write the f开发者_Python百科ollowing 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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号