Module: Parslet::ClassMethods

Defined in:
lib/parslet.rb

Instance Method Summary collapse

Instance Method Details

#rule(name, opts = {}, &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


102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/parslet.rb', line 102

def rule(name, opts={}, &definition)
  undef_method name if method_defined? name
  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::Entity.new(name, opts[:label], &definition_closure)
  end
end