class HashNestizy::Nestizier
Class that performs the actual hash nesting
Public Class Methods
new(hash_value, nesting_value)
click to toggle source
# File lib/hash_nestizy/nestizier.rb, line 6 def initialize(hash_value, nesting_value) @hash_value = hash_value @nesting_value = nesting_value end
Public Instance Methods
to_nested()
click to toggle source
# File lib/hash_nestizy/nestizier.rb, line 11 def to_nested @hash_value.each_with_object({}) do |(key, value), ac| current = ac current_parent = ac last_key = key if [String, Symbol].any? { |t| key.is_a?(t) } key_parts = key.to_s.split(@nesting_value) key_parts.each do |key_part| break unless current.is_a?(Hash) current_parent = current current, last_key = nested_insert(current, key_part) end end current_parent[last_key] = value end end
Private Instance Methods
get_or_add_child(curr_child, key, default: {})
click to toggle source
# File lib/hash_nestizy/nestizier.rb, line 49 def get_or_add_child(curr_child, key, default: {}) curr_child[key] = default unless curr_child[key] curr_child[key] end
nested_insert(current, key)
click to toggle source
# File lib/hash_nestizy/nestizier.rb, line 33 def nested_insert(current, key) if key.include?('[') key_part_list = key.split('[') key = key_part_list[0] index = key_part_list[-1].to_i list = get_or_add_child(current, key, default: []) current[key] = list current = get_or_add_child(list, index) else current[key] = get_or_add_child(current, key) current = current[key] end [current, key] end