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.

Parameters:

  • name (String, Symbol)
  • type (String, Symbol, nil) (defaults to: nil)
  • default (Object, nil) (defaults to: nil)
  • path (Array<String, Symbol>, nil) (defaults to: nil)


10
11
12
13
14
15
16
# File 'lib/acts_as_nosql/attribute.rb', line 10

def initialize(name, type: nil, default: nil, path: nil)
  @name = name.to_s
  @type = type
  @default = default
  @path = path&.map(&: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



18
19
20
# File 'lib/acts_as_nosql/attribute.rb', line 18

def cast(value)
  type_caster ? type_caster.new.cast(value) : value
end

#read(attr) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/acts_as_nosql/attribute.rb', line 22

def read(attr)
  if path
    attr&.dig(*path)
  else
    attr&.dig(name)
  end
end

#write(attr, value) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/acts_as_nosql/attribute.rb', line 30

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