class RustyKey::RescuedProc

Attributes

finally[RW]
handlers[RW]
otherwise[RW]
prc[RW]
result[RW]

Public Class Methods

new(wrapped, *types, &handler) click to toggle source
# File lib/rusty_key/exception.rb, line 42
def initialize(wrapped, *types, &handler)
  self.handlers = merge_handlers(handler, *types, initial: {})
  self.prc = wrapped
  self.result = nil
end

Public Instance Methods

call() click to toggle source
# File lib/rusty_key/exception.rb, line 58
def call
  begin
    self.result = prc.call
  rescue Exception => e
    if match = handlers.find { |type, handler| e.is_a? type }&.last
      match&.call(e)
    else
      raise e
    end
  else
    otherwise&.call
  ensure
    finally&.call
  end
  result
end
else(&handler) click to toggle source
# File lib/rusty_key/exception.rb, line 53
def else(&handler)
  self.otherwise = handler
  self
end
ensure(&handler) click to toggle source
# File lib/rusty_key/exception.rb, line 79
def ensure(&handler)
  self.finally = handler
  self
end
ensure!(&handler) click to toggle source
# File lib/rusty_key/exception.rb, line 84
def ensure!(&handler)
  self.ensure(&handler)
  self.call
end
rescue(*types, &handler) click to toggle source
# File lib/rusty_key/exception.rb, line 48
def rescue(*types, &handler)
  self.handlers = merge_handlers(handler, *types)
  self
end
to_proc() click to toggle source
# File lib/rusty_key/exception.rb, line 75
def to_proc
  -> { self.call }
end

Private Instance Methods

merge_handlers(handler, *types, initial: handlers) click to toggle source
# File lib/rusty_key/exception.rb, line 31
def merge_handlers(handler, *types, initial: handlers)
  # rescue clause with unspecified type handles StandardError
  types << StandardError if types.empty?
  types.reduce(initial) do |acc, k|
    # rescue clauses should be prioritized by order of declaration, desc
    acc.merge(k => handler) { |k, existing| existing }
  end
end