Class: JsonDumper::KeyTransformer

Inherits:
Object
  • Object
show all
Defined in:
lib/json_dumper/key_transformer.rb

Class Method Summary collapse

Class Method Details

.array_like?(obj) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/json_dumper/key_transformer.rb', line 37

def self.array_like?(obj)
  obj.is_a?(Array) || (defined?(ActiveRecord::Relation) && obj.is_a?(ActiveRecord::Relation))
end

.camelize(string) ⇒ Object



41
42
43
44
45
# File 'lib/json_dumper/key_transformer.rb', line 41

def self.camelize(string)
  string.split('_').each_with_index.map do |word, index|
    index == 0 ? word : word.capitalize
  end.join
end

.keys_to_camelcase(obj) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/json_dumper/key_transformer.rb', line 3

def self.keys_to_camelcase(obj)
  return nil if obj.nil?
  if array_like?(obj)
    return keys_to_camelcase_array(obj)
  end
  result = obj.map do |k, v|
    new_value = if v.respond_to?(:each_pair)
                  keys_to_camelcase(v)
                elsif array_like?(v)
                  keys_to_camelcase_array(v)
                else
                  v
                end
    new_key = if k.is_a?(String)
                camelize(k)
              elsif k.is_a?(Symbol)
                camelize(k.to_s).to_sym
              else
                k
              end
    [new_key, new_value]
  end.to_h
  if defined?(HashWithIndifferentAccess) && obj.is_a?(HashWithIndifferentAccess)
    result = HashWithIndifferentAccess.new(result)
  end
  result
end

.keys_to_camelcase_array(arr) ⇒ Object



31
32
33
34
35
# File 'lib/json_dumper/key_transformer.rb', line 31

def self.keys_to_camelcase_array(arr)
  arr.map do |v|
    v.respond_to?(:each_pair) ? keys_to_camelcase(v) : v
  end
end