class ChartMogul::Utils::HashSnakeCaser

Public Class Methods

new(hash, immutable_keys: []) click to toggle source

Recursively converts CamelCase and camelBack JSON-style hash keys to Rubyish snake_case, suitable for use during instantiation of Ruby model attributes.

# File lib/chartmogul/utils/hash_snake_caser.rb, line 11
def initialize(hash, immutable_keys: [])
  @hash = hash
  @immutable_keys = immutable_keys
end

Public Instance Methods

to_snake_keys(value = @hash) click to toggle source
# File lib/chartmogul/utils/hash_snake_caser.rb, line 16
def to_snake_keys(value = @hash)
  case value
  when Array
    value.map { |v| to_snake_keys(v) }
  when Hash
    snake_hash(value)
  else
    value
  end
end

Private Instance Methods

immutable_check(k,v) click to toggle source
# File lib/chartmogul/utils/hash_snake_caser.rb, line 33
def immutable_check(k,v)
  return v if @immutable_keys.include?(k)

  to_snake_keys(v)
end
snake_hash(value) click to toggle source
# File lib/chartmogul/utils/hash_snake_caser.rb, line 29
def snake_hash(value)
  Hash[value.map { |k, v| [underscore_key(k), immutable_check(k, v)] }]
end
underscore(string) click to toggle source
# File lib/chartmogul/utils/hash_snake_caser.rb, line 49
def underscore(string)
  string.gsub(/::/, '/')
        .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
        .gsub(/([a-z\d])([A-Z])/, '\1_\2')
        .tr('-', '_')
        .downcase
end
underscore_key(k) click to toggle source
# File lib/chartmogul/utils/hash_snake_caser.rb, line 39
def underscore_key(k)
  if k.instance_of?(Symbol)
    underscore(k.to_s).to_sym
  elsif k.instance_of?(String)
    underscore(k)
  else
    k # Can't snakify anything except strings and symbols
  end
end