1

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

pedalpete
  • 21,076
  • 45
  • 128
  • 239

2 Answers2

1

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

Ryan Her
  • 1,067
  • 1
  • 9
  • 14
  • i used the .respond_to, the 'try' wasn't working in an if statement, which I needed to finally output {"month":"<= @input_date.month.text_value % >} – pedalpete Aug 01 '11 at 19:25
0

Don't pass parse results outside the parser context. A SyntaxNode is only for use inside the parser. When you have a successful parse, call a function you've defined on your tree to return a domain object - don't just use the parse tree, that's not what it's for.

cliffordheath
  • 2,536
  • 15
  • 16