views:

37

answers:

3

I've got a view which looks like this:

<p><%= stage.end_date.strftime("%A, %d %B %Y")%></p>

Sometimes stage.end_date returns null and that's ok, but Ruby throws a NoMethodError.

I'm quite new to Ruby so I want to know how I should I deal with missing/null varibles in views

  • Do I need to test for stage.end_date in the view? because that feels ugly
  • Do I need to make sure that stage.end_date isn't null, if so that isn't a job for my view is it?
  • Is there a way I can get ruby not worry out about stage.end_date and not throw an errow?

Advice most welcome

+4  A: 

You can do this a bunch of ways, but here are two:

<p><%= stage.end_date.strftime("%A, %d %B %Y") unless stage.end_date.nil? %></p>

or in your stage model, create:

def end_date_formatted
  return "" if end_date.nil?
  end_date.strftime("%A, %d %B %Y")
end
Jesse Wolgamott
I like the model approach
Brian
+1  A: 

The problem is calling strftime on a nil object. Here is an irb example:

>> t = Time.now
=> Thu Jul 22 16:52:10 -0400 2010
>> x = nil
=> nil
>> puts t.strftime("%A, %d %B %Y")
Thursday, 22 July 2010
=> nil
>> puts x.strftime("%A, %d %B %Y")
NoMethodError: undefined method `strftime' for nil:NilClass
    from (irb):4

When you call a method (like strftime) on an object that may be nil, you will get this error. You can try the following for those cases:

<p><%= stage.end_date.strftime("%A, %d %B %Y") unless stage.end_date.nil? %></p>

if that doesn't work, replace .nil? for .blank?

Hope that helps.

Brian
+3  A: 

Just use the Rails method try. Essentially do this:

stage.end_date.try(:strftime,"%A, %d %B %Y")

When end_date is nil, try will not call the method, and just return nil.

Preston Marshall