Class: ActsAsNosql::Attribute
- Inherits:
-
Object
- Object
- ActsAsNosql::Attribute
- Defined in:
- lib/acts_as_nosql/attribute.rb
Instance Attribute Summary collapse
-
#default ⇒ Object
readonly
Returns the value of attribute default.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#path ⇒ Object
readonly
Returns the value of attribute path.
-
#type ⇒ Object
readonly
Returns the value of attribute type.
-
#type_caster ⇒ Object
readonly
Returns the value of attribute type_caster.
Instance Method Summary collapse
- #cast(value) ⇒ Object
-
#initialize(name, type: nil, default: nil, path: nil) ⇒ Attribute
constructor
A new instance of Attribute.
- #read(attr) ⇒ Object
- #write(attr, value) ⇒ Object
Constructor Details
#initialize(name, type: nil, default: nil, path: nil) ⇒ Attribute
Returns a new instance of Attribute.
6 7 8 9 10 11 12 |
# File 'lib/acts_as_nosql/attribute.rb', line 6 def initialize(name, type: nil, default: nil, path: nil) @name = name.to_s @type = type @default = default @path = path&.map { |p| p.to_s } @type_caster = type ? "ActiveRecord::Type::#{type}".safe_constantize : nil end |
Instance Attribute Details
#default ⇒ Object (readonly)
Returns the value of attribute default.
4 5 6 |
# File 'lib/acts_as_nosql/attribute.rb', line 4 def default @default end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
4 5 6 |
# File 'lib/acts_as_nosql/attribute.rb', line 4 def name @name end |
#path ⇒ Object (readonly)
Returns the value of attribute path.
4 5 6 |
# File 'lib/acts_as_nosql/attribute.rb', line 4 def path @path end |
#type ⇒ Object (readonly)
Returns the value of attribute type.
4 5 6 |
# File 'lib/acts_as_nosql/attribute.rb', line 4 def type @type end |
#type_caster ⇒ Object (readonly)
Returns the value of attribute type_caster.
4 5 6 |
# File 'lib/acts_as_nosql/attribute.rb', line 4 def type_caster @type_caster end |
Instance Method Details
#cast(value) ⇒ Object
14 15 16 |
# File 'lib/acts_as_nosql/attribute.rb', line 14 def cast(value) type_caster ? type_caster.new.cast(value) : value end |
#read(attr) ⇒ Object
18 19 20 21 22 23 24 |
# File 'lib/acts_as_nosql/attribute.rb', line 18 def read(attr) if path attr&.dig(*path) else attr&.dig(name) end end |
#write(attr, value) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/acts_as_nosql/attribute.rb', line 26 def write(attr, value) if path current = attr path[0...-1].each do |key| current[key] ||= {} current = current[key] end current[path.last] = cast(value) else attr[name] = cast(value) end end |