Class: ActsAsNosql::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/acts_as_nosql/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

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

#defaultObject (readonly)

Returns the value of attribute default.



4
5
6
# File 'lib/acts_as_nosql/attribute.rb', line 4

def default
  @default
end

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/acts_as_nosql/attribute.rb', line 4

def name
  @name
end

#pathObject (readonly)

Returns the value of attribute path.



4
5
6
# File 'lib/acts_as_nosql/attribute.rb', line 4

def path
  @path
end

#typeObject (readonly)

Returns the value of attribute type.



4
5
6
# File 'lib/acts_as_nosql/attribute.rb', line 4

def type
  @type
end

#type_casterObject (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