Class: Matchi::Predicate
- Inherits:
-
Object
- Object
- Matchi::Predicate
- Defined in:
- lib/matchi/predicate.rb
Overview
Predicate matcher: passes when a predicate method of the actual value
returns true. The matcher name be_xxx calls xxx?, and have_xxx
calls has_xxx?, with Kernel#public_send bound to the actual value.
The predicate must return true or false; any other value is an error,
not a truthy pass.
Since the actual value answers the call, this matcher depends on the honesty of the object under test. Use it for the object's own documented predicates.
Constant Summary collapse
- NAME =
A matcher name:
be_orhave_, then a letter, then letters, digits or underscores, in any script. It never ends with?or!. /\A(be|have)_\p{Alpha}[\p{Alnum}_]*\z/
Instance Method Summary collapse
-
#initialize(name, *args, **kwargs, &block) ⇒ Predicate
constructor
A new instance of Predicate.
- #match? ⇒ Boolean
- #to_s ⇒ String
Constructor Details
#initialize(name, *args, **kwargs, &block) ⇒ Predicate
Returns a new instance of Predicate.
29 30 31 32 33 34 35 36 37 |
# File 'lib/matchi/predicate.rb', line 29 def initialize(name, *args, **kwargs, &block) @name = String(name) raise ::ArgumentError, "name must match #{NAME.inspect} (got: #{name.inspect})" unless NAME.match?(@name) @method_name = method_name @args = args @kwargs = kwargs @block = block end |
Instance Method Details
#match? ⇒ Boolean
44 45 46 47 48 49 50 51 |
# File 'lib/matchi/predicate.rb', line 44 def match? raise ::ArgumentError, "a block must be provided" unless block_given? result = ::Kernel.instance_method(:public_send).bind_call(yield, @method_name, *@args, **@kwargs, &@block) return result if true.equal?(result) || false.equal?(result) raise ::TypeError, "#{@method_name} must return true or false (got a #{Constant.label(result_class(result))})" end |
#to_s ⇒ String
54 55 56 57 58 59 |
# File 'lib/matchi/predicate.rb', line 54 def to_s arguments = @args.map(&:inspect) + @kwargs.map { |key, value| "#{key}: #{value.inspect}" } arguments << "&block" if @block [@name.tr("_", " "), arguments.join(", ")].reject(&:empty?).join(" ") end |