Module: CamelSnakeKeys

Defined in:
lib/version.rb,
lib/camel_snake_keys.rb

Overview

Convert the keys of hashes in nested structures to camel or snake case.

Constant Summary collapse

VERSION =
'1.1.0'

Class Method Summary collapse

Class Method Details

.camel_keys(data) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
# File 'lib/camel_snake_keys.rb', line 67

def camel_keys(data)
  case data
  when Array
    data.map { |v| camel_keys(v) }
  when Hash
    hash = data.sort_by { |k, _v| k.to_s =~ /_/ ? 1 : 0 }.to_h { |k, v| [if_camelize(k), camel_keys(v)] }
    data.instance_of?(Hash) ? hash : data.class.new(hash)
  else
    data
  end
end

.camelcase(obj) ⇒ Object



18
19
20
21
22
23
# File 'lib/camel_snake_keys.rb', line 18

def camelcase(obj)
  string = +obj.to_s # unfreeze whatever it might be with a leading +
  string.sub!(/^([A-Z])/) { $1.downcase }
  string.gsub!(/_([a-z\d])/) { $1.capitalize }
  string
end

.if_camelize(obj) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/camel_snake_keys.rb', line 44

def if_camelize(obj)
  case obj
  when Symbol
    camelcase(obj.to_s).to_sym
  when String
    camelcase(obj)
  else
    obj
  end
end

.if_underscore(obj) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/camel_snake_keys.rb', line 33

def if_underscore(obj)
  case obj
  when Symbol
    snakecase(obj.to_s).to_sym
  when String
    snakecase(obj)
  else
    obj
  end
end

.snake_keys(data) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# File 'lib/camel_snake_keys.rb', line 55

def snake_keys(data)
  case data
  when Array
    data.map { |v| snake_keys(v) }
  when Hash
    hash = data.sort_by { |k, _v| k.to_s =~ /_/ ? 0 : 1 }.to_h { |k, v| [if_underscore(k), snake_keys(v)] }
    data.instance_of?(Hash) ? hash : data.class.new(hash)
  else
    data
  end
end

.snakecase(obj) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/camel_snake_keys.rb', line 25

def snakecase(obj)
  string    = +obj.to_s
  string[0] = string[0].downcase if string[0]
  string.gsub!(/([A-Z])/) { "_#{$1}" }
  string.downcase!
  string
end

.versionObject



7
8
9
# File 'lib/version.rb', line 7

def self.version
  VERSION
end