Module: Cuprum::Matching::ClassMethods

Included in:
Cuprum::Matcher, Cuprum::Matching
Defined in:
lib/cuprum/matching.rb

Overview

Class methods extend-ed into a class when the module is included.

Instance Method Summary collapse

Instance Method Details

#match(status, error: nil, value: nil) {|result| ... } ⇒ Object

Defines a match clause for the matcher.

Parameters:

  • status (Symbol)

    The status to match. The clause will match a result only if the result has the same status as the match clause.

  • error (Class) (defaults to: nil)

    The type of error to match. If given, the clause will match a result only if the result error is an instance of the given class, or an instance of a subclass.

  • value (Class) (defaults to: nil)

    The type of value to match. If given, the clause will match a result only if the result value is an instance of the given class, or an instance of a subclass.

Yields:

  • The code to execute on a successful match.

Yield Parameters:



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/cuprum/matching.rb', line 27

def match(status, error: nil, value: nil, &block)
  validate_status!(status)
  validate_error!(error)
  validate_value!(value)

  clause  = MatchClause.new(block, error, status, value)
  clauses = match_clauses[status]
  index   = clauses.bsearch_index { |item| clause <= item } || -1

  # Clauses are sorted from most specific to least specific.
  clauses.insert(index, clause)
end

#match_result(result:) ⇒ Object



41
42
43
44
45
# File 'lib/cuprum/matching.rb', line 41

def match_result(result:)
  status_clauses(result.status).find do |clause|
    clause.matches_result?(result: result)
  end
end

#matches_result?(result:) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
51
52
# File 'lib/cuprum/matching.rb', line 48

def matches_result?(result:)
  status_clauses(result.status).reverse_each.any? do |clause|
    clause.matches_result?(result: result)
  end
end

#matches_status?(error:, status:, value:) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
# File 'lib/cuprum/matching.rb', line 55

def matches_status?(error:, status:, value:)
  status_clauses(status).reverse_each.any? do |clause|
    clause.matches_details?(error: error, value: value)
  end
end