Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/cognizant/util/transform_hash_keys.rb

Instance Method Summary collapse

Instance Method Details

#deep_flatten_dashes_and_symbolize_keys!Object

Destructively convert all dashes in keys to underscores and then the keys to symbols, as long as they respond to ‘to_sym`. This includes the keys from the root hash and from all nested hashes.



30
31
32
# File 'lib/cognizant/util/transform_hash_keys.rb', line 30

def deep_flatten_dashes_and_symbolize_keys!
  deep_transform_keys!{ |key| key.gsub("-", "_").to_sym  rescue key }
end

#deep_stringify_keys!Object

Destructively convert all keys to strings, as long as they respond to ‘to_s`. This includes the keys from the root hash and from all nested hashes.



16
17
18
# File 'lib/cognizant/util/transform_hash_keys.rb', line 16

def deep_stringify_keys!
  deep_transform_keys!{ |key| key.to_s rescue key }
end

#deep_symbolize_keys!Object

Destructively convert all keys to symbols, as long as they respond to ‘to_sym`. This includes the keys from the root hash and from all nested hashes.



23
24
25
# File 'lib/cognizant/util/transform_hash_keys.rb', line 23

def deep_symbolize_keys!
  deep_transform_keys!{ |key| key.to_sym rescue key }
end

#deep_transform_keys!(&block) ⇒ Object

Destructively convert all keys by using the block operation. This includes the keys from the root hash and from all nested hashes.



5
6
7
8
9
10
11
# File 'lib/cognizant/util/transform_hash_keys.rb', line 5

def deep_transform_keys!(&block)
  keys.each do |key|
    value = delete(key)
    self[yield(key)] = value.is_a?(Hash) ? value.deep_transform_keys!(&block) : value
  end
  self
end