Class: Dry::Data::Struct
- Inherits:
-
Object
- Object
- Dry::Data::Struct
- Defined in:
- lib/dry/data/struct.rb
Direct Known Subclasses
Class Attribute Summary collapse
-
.constructor ⇒ Object
readonly
Returns the value of attribute constructor.
Class Method Summary collapse
- .attribute(name, type) ⇒ Object
- .attributes(new_schema) ⇒ Object
- .inherited(klass) ⇒ Object
- .new(attributes) ⇒ Object
- .schema ⇒ Object
Instance Method Summary collapse
- #[](name) ⇒ Object
-
#initialize(attributes) ⇒ Struct
constructor
A new instance of Struct.
- #to_hash ⇒ Object (also: #to_h)
Constructor Details
#initialize(attributes) ⇒ Struct
Returns a new instance of Struct.
39 40 41 |
# File 'lib/dry/data/struct.rb', line 39 def initialize(attributes) attributes.each { |key, value| instance_variable_set("@#{key}", value) } end |
Class Attribute Details
.constructor ⇒ Object (readonly)
Returns the value of attribute constructor.
5 6 7 |
# File 'lib/dry/data/struct.rb', line 5 def constructor @constructor end |
Class Method Details
.attribute(name, type) ⇒ Object
13 14 15 |
# File 'lib/dry/data/struct.rb', line 13 def self.attribute(name, type) attributes(name => type) end |
.attributes(new_schema) ⇒ Object
17 18 19 20 21 22 23 24 25 26 |
# 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) ⇒ Object
8 9 10 11 |
# File 'lib/dry/data/struct.rb', line 8 def self.inherited(klass) super Data.register_class(klass) unless klass == Value end |
.new(attributes) ⇒ Object
33 34 35 36 37 |
# File 'lib/dry/data/struct.rb', line 33 def self.new(attributes) super(constructor[attributes]) rescue SchemaError, SchemaKeyError => e raise StructError, "[#{self}.new] #{e.}" end |
.schema ⇒ Object
28 29 30 31 |
# File 'lib/dry/data/struct.rb', line 28 def self.schema super_schema = superclass.respond_to?(:schema) ? superclass.schema : {} super_schema.merge(@schema || {}) end |
Instance Method Details
#[](name) ⇒ Object
43 44 45 |
# File 'lib/dry/data/struct.rb', line 43 def [](name) public_send(name) end |
#to_hash ⇒ Object Also known as: to_h
47 48 49 50 51 52 |
# 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 |