Confident Ruby - deliver result by yield a status object

20 Jul 2019

class StatusObject
  def self.success() new(:success) end
  def self.redundant() new(:redundant) end
  def self.failed(error) new(:failed, error) end

  attr_reader :error
  
  def on_success
    yield if @status == :success
  end
  
  def on_redundant
    yield if @status = :redundant
  end
  
  def on_failed
    yield(error) if @status == :failed
  end
end

class ProcessObject
  def proceed
    if conditon
      yield StatusObject.redundant
    else
      yield StatusObject.success
    else
  rescue => error
  	yield StatusObject.failed(error)
  end
end
  
ProcesObject.new.proceed do |result|
  result.on_success do
    # do things when success
  end
  
  result.on_redundant do
    # do things when redundant
  end
  
  result.on_failed do
    # do things when failed
  end
end