Module: SexpPath::Traverse

Included in:
Sexp
Defined in:
lib/sexp_path/traverse.rb

Instance Method Summary collapse

Instance Method Details

#capture_as(name) ⇒ Object Also known as: %

Sets a named capture for the Matcher. If a SexpResult is returned any named captures will be available it.



57
58
59
60
# File 'lib/sexp_path/traverse.rb', line 57

def capture_as(name)
  @capture_name = name
  self
end

#replace_sexp(pattern, data = {}, &block) ⇒ Object

Searches for the pattern yielding a SexpResult for each match, and replacing it with the result of the block.

There is no guarantee that the result will or will not be the same object passed in, meaning this mutates, or replaces the original sexp.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/sexp_path/traverse.rb', line 39

def replace_sexp(pattern, data={}, &block)
  return self unless pattern.is_a? Sexp
  
  if pattern.satisfy?(self, data)
    return block.call(SexpResult.new(self, data))
  end
  
  self.each_with_index do |subset, i|
    case subset
      when Sexp then self[i] = (subset.replace_sexp(pattern, data, &block))
    end
  end
  
  return self
end

#search(pattern, data = {}) ⇒ Object Also known as: /

Searches for the pattern returning a SexpCollection containing a SexpResult for each match.

Example:

s(:a, s(:b)) / Q{ s(:b) } => [s(:b)]


8
9
10
11
12
# File 'lib/sexp_path/traverse.rb', line 8

def search(pattern, data={})
  collection = SexpCollection.new
  search_each(pattern,data){|match| collection << match}
  collection
end

#search_each(pattern, data = {}, &block) ⇒ Object

Searches for the pattern yielding a SexpResult for each match.



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/sexp_path/traverse.rb', line 18

def search_each(pattern, data={}, &block)
  return false unless pattern.is_a? Sexp
  
  if pattern.satisfy?(self, data)
    block.call(SexpResult.new(self, data))
  end
  
  self.each do |subset|
    case subset
      when Sexp then subset.search_each(pattern, data, &block)
    end
  end
end