Module: Rudash::NestedPathCreator

Defined in:
lib/utils/nested_path_creator.rb

Class Method Summary collapse

Class Method Details

.create_path_if_not_exist(object, resolved_path) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/utils/nested_path_creator.rb', line 11

def self.create_path_if_not_exist(object, resolved_path)
  path = R_.head(resolved_path)
  return nil if !resolved_path.is_a?(Array) || R_.nil?(path)

  path_key = Utils.match_number?(path) ? path.to_i : path.to_sym
  rest_paths = R_.tail(resolved_path)
  next_path = R_.head(rest_paths)
  value = R_.get(object, path)

  if R_.nil?(value) || (!value.is_a?(Hash) && !value.is_a?(Array))
    # If the next path item is numeric (index)
    # then we want to create an array otherwise we create a hash
    object[path_key] = next_path && Utils.match_number?(next_path) ? [] : {}
  end

  # Do the same recursively for next path
  # until getting to the last path item
  self.create_path_if_not_exist(
    R_.get(object, path),
    rest_paths
  )
end