Class: Flows::Contract::Predicate

Inherits:
Flows::Contract show all
Defined in:
lib/flows/contract/predicate.rb

Overview

Makes a contract from 1-argument lambda.

Such lambdas works like predicates.

Examples:

positive_check = Flows::Contract::Predicate.new 'must be a positive integer' do |x|
  x.is_a?(Integer) && x > 0
end

positive_check === 10
# => true

positive_check === -100
# => false

Since:

  • 0.4.0

Instance Method Summary collapse

Methods inherited from Flows::Contract

#===, #check, make, #to_proc, #transform, #transform!

Constructor Details

#initialize(error_message) {|object| ... } ⇒ Predicate

Returns a new instance of Predicate.

Parameters:

  • error_message

    error message if check fails

Yields:

  • (object)

    lambda to wrap into a contract

Yield Returns:

  • (Boolean)

    lambda should return a boolean

Since:

  • 0.4.0



21
22
23
24
# File 'lib/flows/contract/predicate.rb', line 21

def initialize(error_message, &block)
  @error_message = error_message
  @block = block
end

Instance Method Details

#check!(other) ⇒ Object

Raises:

See Also:

Since:

  • 0.4.0



27
28
29
30
31
# File 'lib/flows/contract/predicate.rb', line 27

def check!(other)
  raise Error.new(other, @error_message) unless @block === other

  true
end