Class: Dry::Types::Struct
- Inherits:
-
Object
- Object
- Dry::Types::Struct
show all
- Defined in:
- lib/dry/types/struct.rb
Class Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(attributes) ⇒ Struct
Returns a new instance of Struct.
59
60
61
|
# File 'lib/dry/types/struct.rb', line 59
def initialize(attributes)
attributes.each { |key, value| instance_variable_set("@#{key}", value) }
end
|
Class Attribute Details
.constructor ⇒ Object
Returns the value of attribute constructor.
5
6
7
|
# File 'lib/dry/types/struct.rb', line 5
def constructor
@constructor
end
|
Class Method Details
.attribute(name, type) ⇒ Object
24
25
26
|
# File 'lib/dry/types/struct.rb', line 24
def self.attribute(name, type)
attributes(name => type)
end
|
.attributes(new_schema) ⇒ Object
28
29
30
31
32
33
34
35
36
37
38
|
# File 'lib/dry/types/struct.rb', line 28
def self.attributes(new_schema)
prev_schema = schema
@schema = prev_schema.merge(new_schema)
@constructor = Types['coercible.hash'].public_send(constructor_type, schema)
attr_reader(*(new_schema.keys - prev_schema.keys))
equalizer.instance_variable_get('@keys').concat(schema.keys).uniq!
self
end
|
.constructor_type(type = :strict) ⇒ Object
40
41
42
|
# File 'lib/dry/types/struct.rb', line 40
def self.constructor_type(type = :strict)
@constructor_type ||= type
end
|
.equalizer ⇒ Object
20
21
22
|
# File 'lib/dry/types/struct.rb', line 20
def self.equalizer
@equalizer
end
|
.inherited(klass) ⇒ Object
8
9
10
11
12
13
14
15
16
17
18
|
# File 'lib/dry/types/struct.rb', line 8
def self.inherited(klass)
super
klass.instance_variable_set('@equalizer', Equalizer.new)
klass.send(:include, klass.equalizer)
unless klass == Value
klass.instance_variable_set('@constructor', Types['coercible.hash'])
Types.register_class(klass)
end
end
|
.new(attributes = {}) ⇒ Object
49
50
51
52
53
54
55
56
57
|
# File 'lib/dry/types/struct.rb', line 49
def self.new(attributes = {})
if attributes.is_a?(self)
attributes
else
super(constructor[attributes])
end
rescue SchemaError, SchemaKeyError => e
raise StructError, "[#{self}.new] #{e.message}"
end
|
.schema ⇒ Object
44
45
46
47
|
# File 'lib/dry/types/struct.rb', line 44
def self.schema
super_schema = superclass.respond_to?(:schema) ? superclass.schema : {}
super_schema.merge(@schema || {})
end
|
Instance Method Details
#[](name) ⇒ Object
63
64
65
|
# File 'lib/dry/types/struct.rb', line 63
def [](name)
public_send(name)
end
|
#to_hash ⇒ Object
Also known as:
to_h
67
68
69
70
71
72
|
# File 'lib/dry/types/struct.rb', line 67
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
|