Class: ActiveSet::Instructions::Entry::KeyPath

Inherits:
Object
  • Object
show all
Defined in:
lib/active_set/instructions/entry/keypath.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ KeyPath

Returns a new instance of KeyPath.



13
14
15
16
17
# File 'lib/active_set/instructions/entry/keypath.rb', line 13

def initialize(path)
  # `path` can be an Array (e.g. [:parent, :child, :grandchild])
  # or a String (e.g. 'parent.child.grandchild')
  @path = Array.wrap(path).map(&:to_s).flat_map { |x| x.split('.') }
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



11
12
13
# File 'lib/active_set/instructions/entry/keypath.rb', line 11

def path
  @path
end

Instance Method Details

#associations_arrayObject



31
32
33
34
# File 'lib/active_set/instructions/entry/keypath.rb', line 31

def associations_array
  return [] unless @path.any?
  @path.slice(0, @path.length - 1)
end

#associations_hashObject



36
37
38
39
# File 'lib/active_set/instructions/entry/keypath.rb', line 36

def associations_hash
  return {} unless @path.any?
  associations_array.reverse.reduce({}) { |a, e| { e => a } }
end

#attributeObject



19
20
21
22
23
# File 'lib/active_set/instructions/entry/keypath.rb', line 19

def attribute
  attribute = @path.last
  return attribute.sub(operator_regex, '') if attribute&.match operator_regex
  attribute
end

#operatorObject



25
26
27
28
29
# File 'lib/active_set/instructions/entry/keypath.rb', line 25

def operator
  attribute = @path.last
  return attribute[operator_regex, 1] if attribute&.match operator_regex
  '=='
end

#resource_for(item:) ⇒ Object



47
48
49
50
51
# File 'lib/active_set/instructions/entry/keypath.rb', line 47

def resource_for(item:)
  associations_array.reduce(item, :try)
rescue
  nil
end

#titleizedObject



53
54
55
# File 'lib/active_set/instructions/entry/keypath.rb', line 53

def titleized
  @path.map(&:titleize).join(' ')
end

#value_for(item:) ⇒ Object



41
42
43
44
45
# File 'lib/active_set/instructions/entry/keypath.rb', line 41

def value_for(item:)
  resource_for(item: item).send(attribute)
rescue
  nil
end