Search code examples
ruby-on-railsnulltreetop

Why is this returning an 'undefined method' error


I'm getting started with Treetop (though I don't think this is a treetop error) and I'm trying to parse a simple date field.

I am trying to figure out if the date includes a month, and if so return that. So i pass my parsed tree to my view and say


< % if !@input_date.month.nil? % >

      < %= @input_date.month.text_value % >

<% end %>

in my @input_date, the month does not exist, so I was expecting to have no output, but instead I'm getting an error

undefined method 'month' for #<Treetop::SyntaxNode:0x41a0240>

I've also tried to use .exists, but I get the same result.

Why is this?? Is there another way to check for the existence of the month??


Solution

  • If you want to check the existence of a method you can use object.respond_to?(:method_name). It looks like 'month' method doesn't exist in your example.

    You can also use 'try' method if what you want is to test if the object is nil, then call a method.

    <%= object.try(:method, :param) %> instead of <% if !object.nil? %>.....

    I got it from here