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 |
# 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) # create a collection at the keypath collection = keypath.to_collection # set the value in the collection depth = '' keypath.to_a.each do |e| # walk down set and make up the right place to assign if e.is_number? key = "#{e}" else key = ":#{e}" end depth << "[#{key}]" end # assign it if value.is_a? String eval "collection#{depth} = '#{value}'" else eval "collection#{depth} = #{value}" end # merge the new collection into self self.deep_merge!(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 |