Sha256: cad1af07a72a5cf7cdc4fba8fadc374daf4562a0fae5f5fa2dd25531328c8b75

Contents?: true

Size: 645 Bytes

Versions: 2

Compression:

Stored size: 645 Bytes

Contents

module Terror
  def errors(from: ::StandardError, &blk)
    ErrorBuilder.new(self, from).instance_exec(&blk)
  end

  def const_missing(name)
    return super unless name.to_s.end_with?("Error")

    const_set(name, Class.new(StandardError))
  end

  class ErrorBuilder < BasicObject
    def initialize(klass, from)
      @klass = klass
      @from = from
    end

    def method_missing(name, **kwargs, &blk)
      error = ::Class.new(kwargs.fetch(:from, @from), &blk)

      if kwargs.has_key?(:message)
        error.class_eval("def message; '#{kwargs.fetch(:message)}'; end")
      end

      @klass.const_set(name, error)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
terror-0.4.0 lib/terror.rb
terror-0.2.0 lib/terror.rb