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.



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

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

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



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

def path
  @path
end

Instance Method Details

#associations_arrayObject



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

def associations_array
  @path.slice(0, @path.length - 1)
end

#associations_hashObject



34
35
36
# File 'lib/active_set/instructions/entry/keypath.rb', line 34

def associations_hash
  associations_array.reverse.reduce({}) { |a, e| { e => a } }
end

#attributeObject



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

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

#operatorObject



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

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

#resource_for(item:) ⇒ Object



44
45
46
47
48
# File 'lib/active_set/instructions/entry/keypath.rb', line 44

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

#titleizedObject



50
51
52
# File 'lib/active_set/instructions/entry/keypath.rb', line 50

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

#value_for(item:) ⇒ Object



38
39
40
41
42
# File 'lib/active_set/instructions/entry/keypath.rb', line 38

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