Class: ActiveSet::Instructions::Entry::KeyPath
- Inherits:
-
Object
- Object
- ActiveSet::Instructions::Entry::KeyPath
- Defined in:
- lib/active_set/instructions/entry/keypath.rb
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
Instance Method Summary collapse
- #associations_array ⇒ Object
- #associations_hash ⇒ Object
- #attribute ⇒ Object
-
#initialize(path) ⇒ KeyPath
constructor
A new instance of KeyPath.
- #operator ⇒ Object
- #resource_for(item:) ⇒ Object
- #titleized ⇒ Object
- #value_for(item:) ⇒ Object
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
#path ⇒ Object (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_array ⇒ Object
30 31 32 |
# File 'lib/active_set/instructions/entry/keypath.rb', line 30 def associations_array @path.slice(0, @path.length - 1) end |
#associations_hash ⇒ Object
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 |
#attribute ⇒ Object
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 |
#operator ⇒ Object
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 |
#titleized ⇒ Object
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 |