module SexpPath::Traverse

Public Instance Methods

%(name)
Alias for: capture_as
/(pattern, data={})
Alias for: search
capture_as(name) click to toggle source

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

# File lib/sexp_path/traverse.rb, line 57
def capture_as(name)
  @capture_name = name
  self
end
Also aliased as: %
replace_sexp(pattern, data={}, &block) click to toggle source

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.

# 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_each(pattern, data={}, &block) click to toggle source

Searches for the pattern yielding a SexpResult for each match.

# 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

Private Instance Methods

capture_match(matching_object, data) click to toggle source
# File lib/sexp_path/traverse.rb, line 64
def capture_match(matching_object, data)
  if @capture_name
    data[@capture_name] = matching_object
  end

  data
end