Class: Ataulfo::PatternMatching::Matcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ataulfo/pattern_matching.rb

Instance Method Summary collapse

Constructor Details

#initialize(object, pattern) ⇒ Matcher

Returns a new instance of Matcher.



20
21
22
23
24
25
26
27
28
29
# File 'lib/ataulfo/pattern_matching.rb', line 20

def initialize(object, pattern)
  @object                      = object
  @pattern_vars                = pattern.select { |_, v| v.is_a? Var }
  inner_matches                = pattern.select { |_, v| v.is_a? Hash }
  fixed_values                 = pattern.select { |_, v| !v.is_a?(Var) && !v.is_a?(Hash) }
  @object_respond_to_methods   = pattern.keys.all? { |k| @object.respond_to? k }
  @object_answers_right_values = fixed_values.all? { |k, v| @object.send(k) == v }

  @matchers = inner_matches.map { |k, v| Matcher.new(object.send(k), v) }
end

Instance Method Details

#fill_varsObject



35
36
37
38
# File 'lib/ataulfo/pattern_matching.rb', line 35

def fill_vars
  @pattern_vars.each { |k, v| v.value = @object.send k }
  @matchers.each(&:fill_vars)
end

#matches?Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/ataulfo/pattern_matching.rb', line 31

def matches?
  @matchers.all?(&:matches?) if @object_respond_to_methods && @object_answers_right_values
end