Class: Dry::Matcher::Case

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/matcher/case.rb

Overview

Case object contains logic for pattern matching and resolving result from matched pattern

Constant Summary collapse

DEFAULT_RESOLVE =
-> result { result }

Instance Method Summary collapse

Constructor Details

#initialize(match: Undefined, resolve: DEFAULT_RESOLVE, &block) ⇒ Case

Returns a new instance of Case.

Parameters:

  • match (#call) (defaults to: Undefined)

    callable used to test given pattern against value

  • resolve (#call) (defaults to: DEFAULT_RESOLVE)

    callable used to resolve value into a result



12
13
14
15
16
17
18
19
20
# File 'lib/dry/matcher/case.rb', line 12

def initialize(match: Undefined, resolve: DEFAULT_RESOLVE, &block)
  @match = block || proc do |value, patterns|
    if match.(value, *patterns)
      resolve.(value)
    else
      Undefined
    end
  end
end

Instance Method Details

#call(value, patterns = EMPTY_ARRAY) {|v| ... } ⇒ Object, Dry::Core::Constants::Undefined

Returns Either the yield result or Undefined if match wasn’t successful.

Parameters:

  • value (Object)

    Value to match

  • patterns (Array<Object>) (defaults to: EMPTY_ARRAY)

    Optional list of patterns to match against

Yield Parameters:

  • v (Object)

    Resolved value if match succeeds

Returns:

  • (Object, Dry::Core::Constants::Undefined)

    Either the yield result or Undefined if match wasn’t successful



27
28
29
# File 'lib/dry/matcher/case.rb', line 27

def call(value, patterns = EMPTY_ARRAY, &block)
  Undefined.map(@match.(value, patterns), &block)
end