Class: Mona::ResultMatch

Inherits:
Object
  • Object
show all
Defined in:
lib/mona/result_match.rb

Overview

Use ResultMatch.call to respond to result success or failure

ResultMatch.call(result) do |r|

r.ok                  { |value| ... }
r.err(reason, **meta) { |failure, reason, **meta| ... }
r.err(**meta)         { |failure, reason, **meta| ... }
r.err(reason)         { |failure, reason, **meta| ... }
r.err                 { |failure, reason, **meta| ... }

end

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(result) ⇒ ResultMatch

Returns a new instance of ResultMatch.



16
17
18
19
# File 'lib/mona/result_match.rb', line 16

def initialize(result)
  @throw = Object.new
  @result = result
end

Class Method Details

.call(result) ⇒ Object



14
# File 'lib/mona/result_match.rb', line 14

def self.call(result, &) = new(result).call(&)

Instance Method Details

#callObject



21
22
23
24
25
26
# File 'lib/mona/result_match.rb', line 21

def call
  catch @throw do
    yield self
    raise NoMatchError, @result
  end
end

#err(match_reason = nil, **match_meta) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/mona/result_match.rb', line 34

def err(match_reason = nil, **match_meta)
  @result.or_else do |failure, reason, **meta|
    # @type var meta: Hash[Symbol, untyped]
    if match_reason?(match_reason, reason) && match_meta?(match_meta, meta)
      throw @throw, yield(failure, reason, **meta)
    end
  end
end

#okObject



28
29
30
31
32
# File 'lib/mona/result_match.rb', line 28

def ok
  @result.and_then do |value|
    throw @throw, yield(value)
  end
end