Class: LookLike::ArrayMatcher

Inherits:
Matcher
  • Object
show all
Defined in:
lib/look_like/array-matcher.rb

Direct Known Subclasses

NestedArrayMatcher

Instance Attribute Summary

Attributes inherited from Matcher

#desc, #name

Instance Method Summary collapse

Constructor Details

#initialize(matchers) ⇒ ArrayMatcher

Returns a new instance of ArrayMatcher.



4
5
6
# File 'lib/look_like/array-matcher.rb', line 4

def initialize(matchers)
  @matchers = matchers
end

Instance Method Details

#element_error(actual, expected) ⇒ Object



9
10
11
# File 'lib/look_like/array-matcher.rb', line 9

def element_error(actual, expected)
  @matchers.find { |matcher| matcher.select(expected) }.error(actual, expected)
end

#error(actual_array, expected_array) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/look_like/array-matcher.rb', line 35

def error(actual_array, expected_array)
  message = []
  if (expected_array.length > actual_array.length)
    message.push("Expected #{ expected_array.length } elements, but found #{actual_array.length}.")
    message.push("Expected : [#{ expected_array.join(", ") }]")
    message.push("Found    : [#{ actual_array.join(", ") }]")
    return message.join(". ")
  end
  actual_array.each_with_index { |actual, index|
    expected = expected_array[index]
    message.push(match_element(actual, expected) ? "" : "x [#{element_error(actual, expected)}]")
  }
  "[#{message.join(", ")}]"
end

#match(actual_array, expected_array) ⇒ Object



18
19
20
# File 'lib/look_like/array-matcher.rb', line 18

def match(actual_array, expected_array)
  match_array(actual_array, expected_array)
end

#match_array(actual_array, expected_array) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/look_like/array-matcher.rb', line 22

def match_array(actual_array, expected_array)
  matches = expected_array.length == actual_array.length
  actual_array.each_with_index { |actual, index|
    expected = expected_array[index]
    matches = matches && match_element(actual, expected)
  }
  matches
end

#match_element(actual, expected) ⇒ Object



14
15
16
# File 'lib/look_like/array-matcher.rb', line 14

def match_element(actual, expected)
  @matchers.find { |matcher| matcher.select(expected) }.match(actual, expected)
end

#negate_error(actual, expected) ⇒ Object



50
51
52
# File 'lib/look_like/array-matcher.rb', line 50

def negate_error(actual, expected)
  "#{"Expected not to match." + error(actual, expected)}"
end

#select(expected) ⇒ Object



31
32
33
# File 'lib/look_like/array-matcher.rb', line 31

def select(expected)
  expected.is_a? Array
end