Module: Buildr::Checks::Matchers

Defined in:
lib/buildr/core/checks.rb

Overview

:nodoc:

Class Method Summary collapse

Class Method Details

.match_using(*names) ⇒ Object

Define matchers that operate by calling a method on the tested object. For example:

foo.should contain(bar)

calls:

foo.contain(bar)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/buildr/core/checks.rb', line 34

def match_using(*names)
  names.each do |name|
    matcher = Class.new do
      # Initialize with expected arguments (i.e. contain(bar) initializes with bar).
      define_method(:initialize) { |*args| @expects = args }
      # Matches against actual value (i.e. foo.should exist called with foo).
      define_method(:matches?) do |actual|
        @actual = actual
        return actual.send("#{name}?", *@expects) if actual.respond_to?("#{name}?")
        return actual.send(name, *@expects) if actual.respond_to?(name)
        raise "You can't check #{actual}, it doesn't respond to #{name}."
      end
      # Some matchers have arguments, others don't, treat appropriately.
      define_method :failure_message do
        args = " " + @expects.map{ |arg| "'#{arg}'" }.join(", ") unless @expects.empty?
        "Expected #{@actual} to #{name}#{args}"
      end
      define_method :negative_failure_message do
        args = " " + @expects.map{ |arg| "'#{arg}'" }.join(", ") unless @expects.empty?
        "Expected #{@actual} to not #{name}#{args}"
      end
    end
    # Define method to create matcher.
    define_method(name) { |*args| matcher.new(*args) }
  end
end