Class: Tree::Matcher

Inherits:
AbstractMatcher show all
Defined in:
lib/modular_tree/matcher.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from AbstractMatcher

#!, #&, #|

Constructor Details

#initialize(*args, &block) ⇒ Matcher

Returns a new instance of Matcher.



30
31
32
33
34
35
# File 'lib/modular_tree/matcher.rb', line 30

def initialize(*args, &block)
  expr = args.size == 1 ? args.first : args
  constrain expr, Proc, Symbol, Class, [Class], true, false, nil
  expr.nil? == block_given? or raise ArgumentError, "Expected either an argument or a block"
  @expr = (expr.nil? ? block : expr)
end

Class Method Details

.new(expr = nil, *args, &block) ⇒ Object



37
38
39
# File 'lib/modular_tree/matcher.rb', line 37

def self.new(expr = nil, *args, &block)
  expr.is_a?(AbstractMatcher) ? expr : super
end

Instance Method Details

#match(node) ⇒ Object



11
# File 'lib/modular_tree/matcher.rb', line 11

def match(node) = match?(node)

#match?(node) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/modular_tree/matcher.rb', line 13

def match?(node)
  case @expr
    when Proc
      @expr.call(node)
    when Symbol
      node.respond_to?(@expr) && node.send(@expr)
    when Class
      node.is_a? @expr
    when Array
      @expr.any? { |klass| node.is_a? klass }
    when true, false
      @expr
  else
    raise ArgumentError, @expr.inspect
  end
end