Class: Evil::Struct
- Inherits:
-
Object
- Object
- Evil::Struct
- Extended by:
- Dry::Initializer::Mixin
- Defined in:
- lib/evil/struct.rb
Overview
Nested structure with type constraints, based on the dry-initializer DSL
Defined Under Namespace
Classes: Attributes
Class Method Summary collapse
-
.attributes(**options, &block) ⇒ self
Shares options between definitions made inside the block.
-
.list_of_attributes ⇒ Array<Symbol>
Returns the list of defined attributes.
-
.new(value = {}) ⇒ Evil::Struct
(also: call, [], load)
Builds a struct from value that respond to
to_horto_hash. -
.option(name, type = nil, as: nil, **opts) ⇒ self
(also: attribute, param)
Declares the attribute.
Instance Method Summary collapse
-
#==(other) ⇒ Boolean
Checks an equality to other object that respond to
to_horto_hash. -
#to_h ⇒ Hash
(also: #to_hash, #dump)
Converts nested structure to hash.
Class Method Details
.attributes(**options, &block) ⇒ self
Shares options between definitions made inside the block
41 42 43 44 |
# File 'lib/evil/struct.rb', line 41 def attributes(**, &block) Attributes.call(self, **, &block) self end |
.list_of_attributes ⇒ Array<Symbol>
Returns the list of defined attributes
50 51 52 |
# File 'lib/evil/struct.rb', line 50 def list_of_attributes @list_of_attributes ||= [] end |
.new(value = {}) ⇒ Evil::Struct Also known as: call, [], load
Builds a struct from value that respond to to_h or to_hash
19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/evil/struct.rb', line 19 def new(value = {}) value if value.instance_of? self.class hash = value if value.is_a? Hash hash ||= value.to_h if value.respond_to? :to_h hash ||= value.to_hash if value.respond_to? :to_hash hash_with_symbolic_keys = hash.each_with_object({}) do |(key, val), obj| obj[key.to_sym] = val end super hash_with_symbolic_keys end |
.option(name, type = nil, as: nil, **opts) ⇒ self Also known as: attribute, param
Declares the attribute
66 67 68 69 |
# File 'lib/evil/struct.rb', line 66 def option(name, type = nil, as: nil, **opts) super.tap { list_of_attributes << (as || name).to_sym } self end |
Instance Method Details
#==(other) ⇒ Boolean
Checks an equality to other object that respond to to_h or to_hash
86 87 88 89 90 91 92 93 94 |
# File 'lib/evil/struct.rb', line 86 def ==(other) if other&.respond_to?(:to_h) to_h == other.to_h elsif other.respond_to?(:to_hash) to_h == other.to_hash else false end end |
#to_h ⇒ Hash Also known as: to_hash, dump
Converts nested structure to hash
Makes conversion through nested hashes, arrays, enumerables, as well as trhough values that respond to to_a, to_h, and to_hash. Doesn’t convert nil.
107 108 109 110 111 112 |
# File 'lib/evil/struct.rb', line 107 def to_h self.class.list_of_attributes.each_with_object({}) do |key, hash| val = send(key) hash[key] = hashify(val) unless val == Dry::Initializer::UNDEFINED end end |