Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using strftime on nil object - how to prevent error?

Tags:

I use strftime to format my raw time as the text of an input box. Usually, when I use strftime I check if the object is nil to prevent errors by using unless nil? However it doesn't seem like I can use that here:

<%= text_field_tag :event_date, @event.event_date.strftime("%m/%d/%Y at %I:%M%p"), :size=>30 %>

I removed the unless because it was throwing an error. How can I make sure this statement works if @event.event_date is nil?

Thanks

like image 384
Matthew Berman Avatar asked Oct 09 '11 21:10

Matthew Berman


1 Answers

One trick is to use try.

<%= text_field_tag :event_date, @event.event_date.try(:strftime, "%m/%d/%Y at %I:%M%p"), :size=>30 %>

Or just check if event_date is set:

<%= text_field_tag :event_date, (@event.event_date && @event.event_date.strftime("%m/%d/%Y at %I:%M%p")), :size=>30 %>
like image 91
rdvdijk Avatar answered Sep 23 '22 21:09

rdvdijk