Using strftime on nil object - how to prevent error?

Matthew Berman picture Matthew Berman · Oct 9, 2011 · Viewed 7.4k times · Source

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

Answer

rdvdijk picture rdvdijk · Oct 9, 2011

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 %>