Module: Enumerable
- Defined in:
- lib/key_path/enumerable/extensions.rb
Instance Method Summary collapse
Instance Method Details
#set_keypath(keypath, value) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/key_path/enumerable/extensions.rb', line 22 def set_keypath(keypath, value) # handle both string and KeyPath::Path forms keypath = keypath.to_keypath if keypath.is_a?(String) keypath_parts = keypath.to_a # Return self if path empty return self if keypath_parts.empty? key = keypath_parts.shift # Just assign value to self when it's a direct path # Remember, this is after calling keypath_parts#shift if keypath_parts.length == 0 key = key.is_number? ? Integer(key) : key.to_sym self[key] = value return self end # keypath_parts.length > 0 # Remember, this is after calling keypath_parts#shift collection = if key.is_number? Array.new else Hash.new end # Remember, this is after calling keypath_parts#shift collection.set_keypath(keypath_parts.join('.'), value) # merge the new collection into self self[key] = collection end |
#value_at_keypath(keypath) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/key_path/enumerable/extensions.rb', line 3 def value_at_keypath(keypath) keypath = keypath.to_s if keypath.is_a?(KeyPath::Path) parts = keypath.split '.', 2 # if it's an array, call the index if self[parts[0].to_i] match = self[parts[0].to_i] else match = self[parts[0]] || self[parts[0].to_sym] end if !parts[1] || match.nil? return match else return match.value_at_keypath(parts[1]) end end |