Class: Definition::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/definition/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil, **kwargs) ⇒ Model

Returns a new instance of Model.

Raises:



48
49
50
51
52
53
# File 'lib/definition/model.rb', line 48

def initialize(hash = nil, **kwargs)
  result = self.class.conform(hash || kwargs)
  raise InvalidModelError.new(result) unless result.passed?

  @_attributes = result.value.freeze
end

Class Method Details

._define_attr_accessor(key) ⇒ Object



33
34
35
36
37
# File 'lib/definition/model.rb', line 33

def _define_attr_accessor(key)
  define_method(key) do
    @_attributes.fetch(key, nil)
  end
end

._definitionObject



39
40
41
42
43
44
45
# File 'lib/definition/model.rb', line 39

def _definition
  @_definition ||= if superclass == ::Definition::Model
                     ::Definition.Keys {}
                   else
                     superclass._definition.dup
                   end
end

.conform(value) ⇒ Object



15
16
17
# File 'lib/definition/model.rb', line 15

def conform(value)
  _definition.conform(value)
end

.option(option_name) ⇒ Object



29
30
31
# File 'lib/definition/model.rb', line 29

def option(option_name)
  _definition.option(option_name)
end

.optional(key, definition, **opts) ⇒ Object



24
25
26
27
# File 'lib/definition/model.rb', line 24

def optional(key, definition, **opts)
  _define_attr_accessor(key)
  _definition.optional(key, definition, **opts)
end

.required(key, definition) ⇒ Object



19
20
21
22
# File 'lib/definition/model.rb', line 19

def required(key, definition)
  _define_attr_accessor(key)
  _definition.required(key, definition)
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



59
60
61
62
63
# File 'lib/definition/model.rb', line 59

def ==(other)
  return false unless other.is_a?(self.class)

  @_attributes.hash == other.instance_variable_get(:@_attributes).hash
end

#hashObject



66
67
68
# File 'lib/definition/model.rb', line 66

def hash
  @_attributes.hash
end

#new(**kwargs) ⇒ Object



55
56
57
# File 'lib/definition/model.rb', line 55

def new(**kwargs)
  self.class.new(**to_h.merge!(kwargs))
end

#to_hObject



70
71
72
73
74
# File 'lib/definition/model.rb', line 70

def to_h
  _deep_transform_values_in_object(@_attributes) do |value|
    value.is_a?(::Definition::Model) ? value.to_h : value
  end
end