Class: SafeOperation

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/safe_operation.rb,
lib/safe_operation/failure.rb,
lib/safe_operation/success.rb,
lib/safe_operation/version.rb

Defined Under Namespace

Classes: Failure, Success

Constant Summary collapse

VERSION =
"2.0.0"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(success: nil, failure: nil) ⇒ SafeOperation

Returns a new instance of SafeOperation.



31
32
33
# File 'lib/safe_operation.rb', line 31

def initialize(success: nil, failure: nil)
  @result = success ? Success.new(success) : Failure.new(failure)
end

Class Method Details

.failure(value) ⇒ Object



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

def failure(value)
  new(failure: value)
end

.runObject



14
15
16
17
18
# File 'lib/safe_operation.rb', line 14

def run
  success(yield)
rescue StandardError => exception
  failure(exception)
end

.success(value) ⇒ Object



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

def success(value)
  new(success: value)
end

Instance Method Details

#and_then(&block) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/safe_operation.rb', line 51

def and_then(&block)
  if success?
    self.class.success(block.call(value))
  else
    self
  end
end

#or_else(&block) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/safe_operation.rb', line 59

def or_else(&block)
  if success?
    self
  else
    self.class.failure(block.call(value))
  end
end

#value_or(fallback_value) ⇒ Object



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

def value_or(fallback_value)
  if success?
    value
  else
    fallback_value
  end
end

#value_or_else(&fallback_block) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/safe_operation.rb', line 43

def value_or_else(&fallback_block)
  if success?
    value
  else
    fallback_block.call(value)
  end
end