class Reasonable::Value

Constants

VERSION

Public Class Methods

inherited(subklass) click to toggle source
# File lib/reasonable/value.rb, line 40
def inherited(subklass)
  config.each do |name, config|
    subklass.attribute(name, config[:type], options: config[:options])
  end
end
new(attributes = {}) click to toggle source
# File lib/reasonable/value.rb, line 14
def initialize(attributes = {})
  @attributes = {}

  self.class.send(:config).each do |name, config|
    options = config[:options]
    if options[:optional]
      attributes[name] = options[:default] if attributes[name].nil?
      next if attributes[name].nil?
    end

    type_error(name, config[:type], NilClass) if attributes[name].nil?

    @attributes[name] = coerce(attributes, name, config)
  end
end
new(object = {}) click to toggle source
Calls superclass method
# File lib/reasonable/value.rb, line 36
def new(object = {})
  Try.(MethodName.(self), object) || super(object)
end

Protected Class Methods

attribute(name, type, **options) click to toggle source
# File lib/reasonable/value.rb, line 48
def attribute(name, type, **options)
  mutex.synchronize { config[name] = { type: type, options: options } }

  define_method(name) { @attributes[name] }
end

Private Class Methods

config() click to toggle source
# File lib/reasonable/value.rb, line 62
def config
  return @config if defined?(@config)

  @config = {}
end
mutex() click to toggle source
# File lib/reasonable/value.rb, line 56
def mutex
  return @mutex if defined?(@mutex)

  @mutex = Thread::Mutex.new
end

Public Instance Methods

<=>(other) click to toggle source
# File lib/reasonable/value.rb, line 10
def <=>(other)
  @attributes <=> other.instance_variable_get(:@attributes)
end
to_hash() click to toggle source
# File lib/reasonable/value.rb, line 30
def to_hash
  @attributes
end

Private Instance Methods

coerce(attributes, name, config) click to toggle source
# File lib/reasonable/value.rb, line 72
def coerce(attributes, name, config)
  Coercer.(config[:type], attributes[name])
rescue TypeError
  type_error(name, config[:type], attributes[name].class)
end
type_error(name, expected, actual) click to toggle source
# File lib/reasonable/value.rb, line 78
def type_error(name, expected, actual)
  raise(
    TypeError,
    "expected :#{name} to be a #{expected} but was a #{actual}"
  )
end