module Localer::Ext::Hash

Extend Hash through refinements

Public Instance Methods

_deep_transform_keys_in_object(object) { |key| ... } click to toggle source

support methods for deep transforming nested hashes and arrays

# File lib/localer/ext/hash.rb, line 74
def _deep_transform_keys_in_object(object, &block)
  case object
  when ::Hash
    object.each_with_object({}) do |(key, value), result|
      result[yield(key)] = _deep_transform_keys_in_object(value, &block)
    end
  when Array
    object.map { |e| _deep_transform_keys_in_object(e, &block) }
  else
    object
  end
end
_deep_transform_keys_in_object!(object) { |key| ... } click to toggle source
# File lib/localer/ext/hash.rb, line 58
def _deep_transform_keys_in_object!(object, &block)
  case object
  when ::Hash
    object.keys.each do |key|
      value = object.delete(key)
      object[yield(key)] = _deep_transform_keys_in_object!(value, &block)
    end
    object
  when Array
    object.map! { |e| _deep_transform_keys_in_object!(e, &block) }
  else
    object
  end
end
deep_downcase_keys() click to toggle source
# File lib/localer/ext/hash.rb, line 38
def deep_downcase_keys
  deep_transform_keys do |key|
    begin
      key.downcase
    rescue StandardError
      key
    end
  end
end
deep_merge(other_hash, &block) click to toggle source
# File lib/localer/ext/hash.rb, line 24
def deep_merge(other_hash, &block)
  dup.deep_merge!(other_hash, &block)
end
deep_merge!(other_hash) click to toggle source

From ActiveSupport api.rubyonrails.org/classes/Hash.html#metho

# File lib/localer/ext/hash.rb, line 9
def deep_merge!(other_hash)
  other_hash.each_pair do |current_key, other_value|
    this_value = self[current_key]

    if this_value.is_a?(::Hash) && other_value.is_a?(::Hash)
      this_value.deep_merge!(other_value)
      this_value
    else
      self[current_key] = other_value
    end
  end

  self
end
deep_symbolize_keys() click to toggle source
# File lib/localer/ext/hash.rb, line 28
def deep_symbolize_keys
  deep_transform_keys do |key|
    begin
      key.to_sym
    rescue StandardError
      key
    end
  end
end
deep_transform_keys(&block) click to toggle source
# File lib/localer/ext/hash.rb, line 48
def deep_transform_keys(&block)
  _deep_transform_keys_in_object(self, &block)
end
deep_transform_keys!(&block) click to toggle source
# File lib/localer/ext/hash.rb, line 52
def deep_transform_keys!(&block)
  _deep_transform_keys_in_object!(self, &block)
end