Class: Dry::Types::Struct
- Inherits:
-
Object
- Object
- Dry::Types::Struct
- Defined in:
- lib/dry/types/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
- .constructor_type(type = :strict) ⇒ 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.
47 48 49 |
# File 'lib/dry/types/struct.rb', line 47 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/types/struct.rb', line 5 def constructor @constructor end |
Class Method Details
.attribute(name, type) ⇒ Object
13 14 15 |
# File 'lib/dry/types/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/types/struct.rb', line 17 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)) self end |
.constructor_type(type = :strict) ⇒ Object
28 29 30 |
# File 'lib/dry/types/struct.rb', line 28 def self.constructor_type(type = :strict) @constructor_type ||= type end |
.inherited(klass) ⇒ Object
8 9 10 11 |
# File 'lib/dry/types/struct.rb', line 8 def self.inherited(klass) super Types.register_class(klass) unless klass == Value end |
.new(attributes = {}) ⇒ Object
37 38 39 40 41 42 43 44 45 |
# File 'lib/dry/types/struct.rb', line 37 def self.new(attributes = {}) if attributes.is_a?(self) attributes else super(constructor[attributes]) end rescue SchemaError, SchemaKeyError => e raise StructError, "[#{self}.new] #{e.}" end |
.schema ⇒ Object
32 33 34 35 |
# File 'lib/dry/types/struct.rb', line 32 def self.schema super_schema = superclass.respond_to?(:schema) ? superclass.schema : {} super_schema.merge(@schema || {}) end |
Instance Method Details
#[](name) ⇒ Object
51 52 53 |
# File 'lib/dry/types/struct.rb', line 51 def [](name) public_send(name) end |
#to_hash ⇒ Object Also known as: to_h
55 56 57 58 59 60 |
# File 'lib/dry/types/struct.rb', line 55 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 |