Class: Evil::Struct

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Class Method Details

.attributes(**options, &block) ⇒ self

Shares options between definitions made inside the block

Parameters:

  • options (Hash<Symbol, Object>)

    Shared options

  • block (Proc)

    Block with definitions of attributes

Returns:

  • (self)

    itself



41
42
43
44
# File 'lib/evil/struct.rb', line 41

def attributes(**options, &block)
  Attributes.call(self, **options, &block)
  self
end

.list_of_attributesArray<Symbol>

Returns the list of defined attributes

Returns:

  • (Array<Symbol>)


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

Parameters:

Returns:



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

Parameters:

  • name (#to_sym)

    The name of the key

  • type (#call) (defaults to: nil)

    (nil) The constraint

  • options (Hash)

    a customizable set of options

Returns:

  • (self)


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

Parameters:

  • other (Object)

Returns:

  • (Boolean)


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_hHash 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.

Returns:

  • (Hash)


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