Class: Ward::Matchers::Satisfy

Inherits:
Matcher
  • Object
show all
Defined in:
lib/ward/matchers/satisfy.rb

Overview

Tests whether the validation value satisfies the given block.

If the block returns any value other than false, the matcher will assume that the match passed.

Alternatively, you may pass a Symbol which identifies a method name; the method will be run with it’s return value used to determine if the matcher passed.

Adding an explict error message is advised, since the message generated by Ward isn’t very helpful: “… is invalid”.

Examples:

Matching with a block


class Record
  validate do |record|
    record.name.satisfies do |value, record|
      value == 'Michael Scarn'
    end
  end
end

With a runtime error message


class Record
  validate do |record|
    record.name.satisfies do |value, record|
      value == 'Michael Scarn' || [false, "Ooooh noooo"]
    end
  end
end

Instance Attribute Summary

Attributes inherited from Matcher

#expected, #extra_args

Instance Method Summary collapse

Methods inherited from Matcher

#customise_error_values, error_id

Constructor Details

#initialize(expected = nil, *extra_args, &block) ⇒ Satisfy

Creates a new matcher instance.

Parameters:

  • expected (Object) (defaults to: nil)

    The expected value for the matcher.



42
43
44
# File 'lib/ward/matchers/satisfy.rb', line 42

def initialize(expected = nil, *extra_args, &block)
  super(block, *extra_args)
end

Instance Method Details

#matches?(actual, record = nil) ⇒ Boolean

Returns whether the given value is satisfied by the expected block.

Parameters:

  • actual (Object)

    The validation value.

  • record (Object) (defaults to: nil)

    The full record.

Returns:

  • (Boolean)


55
56
57
58
59
60
61
# File 'lib/ward/matchers/satisfy.rb', line 55

def matches?(actual, record = nil)
  if @expected.arity != 1
    @expected.call(actual, record)
  else
    @expected.call(actual)
  end
end