class Hash

Hash.to_snake_keys

Public Instance Methods

to_snake_keys(value = self) 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/snake_keys.rb, line 7
def to_snake_keys(value = self)
  case value
    when Array
      value.map { |v| to_snake_keys(v) }
    when Hash
      snake_hash(value)
    else
      value
  end
end

Private Instance Methods

snake_hash(value) click to toggle source
# File lib/snake_keys.rb, line 20
def snake_hash(value)
  Hash[value.map { |k, v| [underscore_key(k), to_snake_keys(v)] }]
end
underscore(string) click to toggle source
# File lib/snake_keys.rb, line 34
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/snake_keys.rb, line 24
def underscore_key(k)
  if k.is_a? Symbol
    underscore(k.to_s).to_sym
  elsif k.is_a? String
    underscore(k)
  else
    k # Plissken can't snakify anything except strings and symbols
  end
end