Module: Dorm::Result

Defined in:
lib/dorm/result.rb

Overview

Result monad using Data - inspired by dry-monads

Constant Summary collapse

Success =
Data.define(:value) do
  def success? = true
  def failure? = false

  def bind(&block)
    block.call(value)
  rescue StandardError => e
    Failure.new(error: e.message)
  end

  def map(&block)
    Success.new(value: block.call(value))
  rescue StandardError => e
    Failure.new(error: e.message)
  end

  def value_or(default = nil)
    value
  end
end
Failure =
Data.define(:error) do
  def success? = false
  def failure? = true

  def bind(&block)
    self
  end

  def map(&block)
    self
  end

  def value_or(default = nil)
    default
  end
end

Class Method Summary collapse

Class Method Details

.combine(*results) ⇒ Object

Combine multiple Results



70
71
72
73
74
75
# File 'lib/dorm/result.rb', line 70

def combine(*results)
  failures = results.select(&:failure?)
  return failure(failures.map(&:error).join(', ')) unless failures.empty?

  success(results.map(&:value))
end

.failure(error) ⇒ Object



59
60
61
# File 'lib/dorm/result.rb', line 59

def failure(error)
  Failure.new(error: error)
end

.success(value) ⇒ Object



55
56
57
# File 'lib/dorm/result.rb', line 55

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

.try(&block) ⇒ Object



63
64
65
66
67
# File 'lib/dorm/result.rb', line 63

def try(&block)
  success(block.call)
rescue StandardError => e
  failure(e.message)
end