class Dry::Data::Struct

Attributes

constructor[R]

Public Class Methods

attribute(name, type) click to toggle source
# File lib/dry/data/struct.rb, line 13
def self.attribute(name, type)
  attributes(name => type)
end
attributes(new_schema) click to toggle source
# File lib/dry/data/struct.rb, line 17
def self.attributes(new_schema)
  prev_schema = schema || {}

  @schema = prev_schema.merge(new_schema)
  @constructor = Data['coercible.hash'].strict(schema)

  attr_reader(*(new_schema.keys - prev_schema.keys))

  self
end
inherited(klass) click to toggle source
Calls superclass method
# File lib/dry/data/struct.rb, line 8
def self.inherited(klass)
  super
  Data.register_class(klass) unless klass == Value
end
new(attributes) click to toggle source
Calls superclass method
# File lib/dry/data/struct.rb, line 33
def self.new(attributes)
  super(constructor[attributes])
rescue SchemaError, SchemaKeyError => e
  raise StructError, "[#{self}.new] #{e.message}"
end
new(attributes) click to toggle source
# File lib/dry/data/struct.rb, line 39
def initialize(attributes)
  attributes.each { |key, value| instance_variable_set("@#{key}", value) }
end
schema() click to toggle source
# File lib/dry/data/struct.rb, line 28
def self.schema
  super_schema = superclass.respond_to?(:schema) ? superclass.schema : {}
  super_schema.merge(@schema || {})
end

Public Instance Methods

[](name) click to toggle source
# File lib/dry/data/struct.rb, line 43
def [](name)
  public_send(name)
end
to_h()
Alias for: to_hash
to_hash() click to toggle source
# File lib/dry/data/struct.rb, line 47
def to_hash
  self.class.schema.keys.each_with_object({}) { |key, result|
    value = self[key]
    result[key] = value.respond_to?(:to_hash) ? value.to_hash : value
  }
end
Also aliased as: to_h