Class: Parslet::Atoms::Capture

Inherits:
Base
  • Object
show all
Defined in:
lib/parslet/atoms/capture.rb

Overview

Stores the result of matching an atom against input in the #captures in parse context. Doing so will allow you to pull parts of the ongoing parse out later and use them to match other pieces of input.

Example:

# After this, context.captures[:an_a] returns 'a'
str('a').capture(:an_a)

# Capture and use of the capture: (matches either 'aa' or 'bb')
match['ab'].capture(:first) >> 
  dynamic { |src, ctx| str(ctx.captures[:first]) }

Constant Summary

Constants included from Precedence

Precedence::ALTERNATE, Precedence::BASE, Precedence::LOOKAHEAD, Precedence::OUTER, Precedence::REPETITION, Precedence::SEQUENCE

Instance Attribute Summary collapse

Attributes inherited from Base

#label

Instance Method Summary collapse

Methods inherited from Base

#accept, #cached?, #inspect, #parse, #parse_with_debug, precedence, #setup_and_apply, #to_s, #try

Methods included from CanFlatten

#flatten, #flatten_repetition, #flatten_sequence, #foldl, #merge_fold, #warn_about_duplicate_keys

Methods included from DSL

#>>, #absent?, #as, #capture, #ignore, #maybe, #present?, #repeat, #|

Constructor Details

#initialize(parslet, name) ⇒ Capture

Returns a new instance of Capture.



17
18
19
20
21
# File 'lib/parslet/atoms/capture.rb', line 17

def initialize(parslet, name)
  super()

  @parslet, @name = parslet, name
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



15
16
17
# File 'lib/parslet/atoms/capture.rb', line 15

def name
  @name
end

#parsletObject (readonly)

Returns the value of attribute parslet.



15
16
17
# File 'lib/parslet/atoms/capture.rb', line 15

def parslet
  @parslet
end

Instance Method Details

#apply(source, context, consume_all) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/parslet/atoms/capture.rb', line 23

def apply(source, context, consume_all)
  success, value = result = parslet.apply(source, context, consume_all)

  if success
    context.captures[name.to_sym] = 
      flatten(value)
  end
  
  return result
end

#to_s_inner(prec) ⇒ Object



34
35
36
# File 'lib/parslet/atoms/capture.rb', line 34

def to_s_inner(prec)
  "(#{name.inspect} = #{parslet.to_s(prec)})"
end