Module: Rbdantic::BaseModel::Access
Overview
Accessor and serialization methods
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object
66
67
68
69
|
# File 'lib/rbdantic/base/access.rb', line 66
def method_missing(name, *args, &block)
return [name] if args.empty? && block.nil? && .key?(name)
super
end
|
Instance Method Details
#==(other) ⇒ Object
Also known as:
eql?
56
57
58
|
# File 'lib/rbdantic/base/access.rb', line 56
def ==(other)
other.is_a?(self.class) && model_dump == other.model_dump
end
|
#[](name) ⇒ Object
27
28
29
|
# File 'lib/rbdantic/base/access.rb', line 27
def [](name)
instance_variable_get("@#{name}")
end
|
#[]=(name, value) ⇒ Object
31
32
33
34
|
# File 'lib/rbdantic/base/access.rb', line 31
def []=(name, value)
raise FrozenError, "cannot modify frozen #{self.class.name}" if self.class.model_config.frozen
self.class.fields.key?(name) ? assign_field(name, value) : (name, value)
end
|
#copy(deep: false) ⇒ BaseModel
Create a copy of the model
39
40
41
42
|
# File 'lib/rbdantic/base/access.rb', line 39
def copy(deep: false)
attributes = deep ? deep_copy_value(model_dump) : model_dump
rebuild_instance(attributes, fields_set: Array(@__fields_set__), extra_fields: Array(@__extra_fields__))
end
|
#hash ⇒ Object
62
63
64
|
# File 'lib/rbdantic/base/access.rb', line 62
def hash
model_dump.hash
end
|
#model_dump(**options) ⇒ Object
Also known as:
to_h
9
10
11
|
# File 'lib/rbdantic/base/access.rb', line 9
def model_dump(**options)
Serialization::Dumper.dump(self, **options)
end
|
#model_dump_json(indent: nil, **options) ⇒ Object
15
16
17
|
# File 'lib/rbdantic/base/access.rb', line 15
def model_dump_json(indent: nil, **options)
Serialization::JsonSerializer.dump(self, indent: indent, **options)
end
|
23
24
25
|
# File 'lib/rbdantic/base/access.rb', line 23
def
Array(@__extra_fields__).each_with_object({}) { |name, h| h[name] = instance_variable_get("@#{name}") }
end
|
#model_fields_set ⇒ Object
19
20
21
|
# File 'lib/rbdantic/base/access.rb', line 19
def model_fields_set
Set.new(Array(@__fields_set__))
end
|
#respond_to_missing?(name, include_private = false) ⇒ Boolean
71
72
73
|
# File 'lib/rbdantic/base/access.rb', line 71
def respond_to_missing?(name, include_private = false)
.key?(name) || super
end
|
Create a new model with updated fields
47
48
49
50
51
52
53
54
|
# File 'lib/rbdantic/base/access.rb', line 47
def update(**data)
candidate = self.class.new(model_dump.merge(data))
= candidate..keys
declared_fields = (model_fields_set - Set.new(.keys)) | Set.new(normalized_update_field_names(data))
fields_set = declared_fields | Set.new()
rebuild_instance(candidate.model_dump, fields_set: fields_set.to_a, extra_fields: )
end
|