Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better alternative to this Ruby idiom?

I'm finding myself writing this bit of code in my controllers a lot:

params[:task][:completed_at] = Time.parse(params[:task][:completed_at]) if params[:task][:completed_at]

Don't get hung up on what I'm doing here specifically, because the reasons change every time; but there are many circumstances where I need to check for a value in params and change it before handing it off to create or update_attributes.

Repeating params[:task][:completed_at] three times feels very bad. Is there a better way to do this?

like image 531
Adam Lassek Avatar asked Dec 22 '22 06:12

Adam Lassek


1 Answers

One way to shorten this slightly is:

if c = params[:task][:completed_at]
  params[:task][:completed_at] = Time.parse(c)
end

Or, you might prefer this:

params[:task][:completed_at] &&= Time.parse(params[:task][:completed_at])

In the second case, the assignment will only happen if the left side is "truthy".

like image 160
Alex Reisner Avatar answered Dec 24 '22 19:12

Alex Reisner