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:



44
45
46
47
48
49
# File 'lib/definition/model.rb', line 44

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
# File 'lib/definition/model.rb', line 39

def _definition
  @_definition ||= ::Definition.Keys {}
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?



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

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

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

#hashObject



62
63
64
# File 'lib/definition/model.rb', line 62

def hash
  @_attributes.hash
end

#new(**kwargs) ⇒ Object



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

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

#to_hObject



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

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