Class: SolidObjects::State
- Inherits:
-
Object
- Object
- SolidObjects::State
show all
- Defined in:
- lib/solid_objects/state.rb,
sig/generated/lib/solid_objects/state.rbs
Instance Attribute Summary collapse
Instance Method Summary
collapse
Constructor Details
#initialize(definition, data = nil) ⇒ State
Returns a new instance of State.
44
45
46
47
48
|
# File 'lib/solid_objects/state.rb', line 44
def initialize(definition, data = nil)
@definition = definition
@data = data ? Serialization.deep_copy(data) : {}
apply_defaults
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *arguments) ⇒ Object
72
73
74
75
76
77
78
79
80
81
82
83
|
# File 'lib/solid_objects/state.rb', line 72
def method_missing(name, *arguments)
name_string = name.to_s
if name_string.end_with?("=")
attribute_name = name_string.delete_suffix("=")
return write(attribute_name, arguments.fetch(0)) if arguments.one? && defined_attribute?(attribute_name)
elsif arguments.empty? && defined_attribute?(name)
return fetch(name)
end
super
end
|
Instance Attribute Details
#data ⇒ Object
Returns the value of attribute data.
93
94
95
|
# File 'lib/solid_objects/state.rb', line 93
def data
@data
end
|
#definition ⇒ Object
Returns the value of attribute definition.
93
94
95
|
# File 'lib/solid_objects/state.rb', line 93
def definition
@definition
end
|
Instance Method Details
#apply_defaults ⇒ void
This method returns an undefined value.
96
97
98
99
100
101
102
103
104
|
# File 'lib/solid_objects/state.rb', line 96
def apply_defaults
definition.to_h.each_value do |attribute|
key = attribute.name.to_s
next if data.key?(key)
value = attribute.default.respond_to?(:call) ? attribute.default.call : attribute.default
data[key] = Serialization.deep_copy(value)
end
end
|
#defined_attribute?(name) ⇒ Boolean
107
108
109
|
# File 'lib/solid_objects/state.rb', line 107
def defined_attribute?(name)
definition.to_h.key?(name.to_sym)
end
|
#fetch(name) ⇒ Object
56
57
58
59
60
61
|
# File 'lib/solid_objects/state.rb', line 56
def fetch(name)
key = name.to_s
raise NoMethodError, "undefined state attribute #{name.inspect}" unless defined_attribute?(name)
data.fetch(key)
end
|
#respond_to_missing?(name, include_private = false) ⇒ Boolean
86
87
88
89
|
# File 'lib/solid_objects/state.rb', line 86
def respond_to_missing?(name, include_private = false)
attribute_name = name.to_s.delete_suffix("=")
defined_attribute?(attribute_name) || super
end
|
#to_h ⇒ Hash[String, untyped]
#write(name, value) ⇒ Object
64
65
66
67
68
69
|
# File 'lib/solid_objects/state.rb', line 64
def write(name, value)
key = name.to_s
raise NoMethodError, "undefined state attribute #{name.inspect}" unless defined_attribute?(name)
data[key] = value
end
|