Module: Enumerable

Defined in:
lib/key_path/enumerable/extensions.rb

Instance Method Summary collapse

Instance Method Details

#set_keypath(keypath, value) ⇒ Object



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 24

def set_keypath(keypath, value)
  # handle both string and KeyPath::Path forms
  if keypath.is_a?(String)
    keypath = keypath.to_keypath
  end

  # 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
  eval "collection#{depth} = #{value}"
  
  # 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
21
22
# File 'lib/key_path/enumerable/extensions.rb', line 3

def value_at_keypath(keypath)
  if keypath.is_a?(KeyPath::Path)
    keypath = keypath.to_s
  end

  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] or match.nil?
    return match
  else
    return match.value_at_keypath(parts[1])
  end
end