Module: Parslet::ClassMethods

Defined in:
lib/parslet.rb

Instance Method Summary collapse

Instance Method Details

#rule(name, &definition) ⇒ Object

Define an entity for the parser. This generates a method of the same name that can be used as part of other patterns. Those methods can be freely mixed in your parser class with real ruby methods.

class MyParser
  include Parslet

  rule(:bar) { str('bar') }
  rule(:twobar) do
    bar >> bar
  end

  root :twobar
end


118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/parslet.rb', line 118

def rule(name, &definition)
  define_method(name) do
    @rules ||= {}     # <name, rule> memoization
    return @rules[name] if @rules.has_key?(name)
    
    # Capture the self of the parser class along with the definition.
    definition_closure = proc {
      self.instance_eval(&definition)
    }
    
    @rules[name] = Atoms::Rule.new(name, &definition_closure)
  end
end