Class: Lab42::Result

Inherits:
Object
  • Object
show all
Extended by:
ClassMethods
Defined in:
lib/lab42/result.rb,
lib/lab42/result/errors.rb,
lib/lab42/result/version.rb,
lib/lab42/result/class_methods.rb,
lib/lab42/result/illegal_monitor_state.rb

Defined Under Namespace

Modules: ClassMethods, Errors Classes: IllegalMonitorState

Constant Summary collapse

VERSION =
"0.2.1"

Instance Method Summary collapse

Methods included from ClassMethods

from_rescue, new, ok

Instance Method Details

#deconstructObject



10
11
12
13
14
15
16
# File 'lib/lab42/result.rb', line 10

def deconstruct
  if ok?
    [true, @value]
  else
    [false, @error, @exception]
  end
end

#deconstruct_keysObject



18
# File 'lib/lab42/result.rb', line 18

def deconstruct_keys(*, **) = to_h

#errorObject



35
36
37
38
# File 'lib/lab42/result.rb', line 35

def error
  raise IllegalMonitorState, "must not invoke the error method on an ok result" if ok?
  @error
end

#error?Boolean



32
# File 'lib/lab42/result.rb', line 32

def error? = !@ok

#exceptionObject



40
41
42
43
# File 'lib/lab42/result.rb', line 40

def exception
  raise IllegalMonitorState, "must not invoke the exception method on an ok result" if ok?
  @exception
end

#if_error(&blk) ⇒ Object



24
25
26
# File 'lib/lab42/result.rb', line 24

def if_error &blk
  blk.(@exception, @error) unless ok?
end

#if_ok(&blk) ⇒ Object



28
29
30
# File 'lib/lab42/result.rb', line 28

def if_ok &blk
  blk.(@value) if ok?
end

#ok?Boolean



33
# File 'lib/lab42/result.rb', line 33

def ok? = @ok

#raise!(alternative_exception = nil, &blk) ⇒ Object

Raises:



45
46
47
48
49
# File 'lib/lab42/result.rb', line 45

def raise!(alternative_exception=nil, &blk)
  return @value if ok?
  message = blk ? blk.(@error) : @error
  raise(alternative_exception||@exception, message)
end

#to_hObject



20
21
22
# File 'lib/lab42/result.rb', line 20

def to_h
  {ok: ok?, value: @value, error: @error, exception: @exception}
end

#valueObject



51
52
53
54
# File 'lib/lab42/result.rb', line 51

def value
  raise IllegalMonitorState, "must not invoke the value method on an error result" unless ok?
  @value
end