Module: AI21::Helper

Included in:
Client, HTTP
Defined in:
lib/ai21/helper.rb

Instance Method Summary collapse

Instance Method Details

#camel_to_snake(hash) ⇒ Object



20
21
22
23
24
# File 'lib/ai21/helper.rb', line 20

def camel_to_snake(hash)
  deep_transform_keys!(hash) do |key|
    key.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase.to_sym
  end
end

#deep_transform_keys!(object, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/ai21/helper.rb', line 5

def deep_transform_keys!(object, &block)
  case object
  when Hash
    object.keys.each do |key|
      value = object.delete(key)
      object[yield(key)] = deep_transform_keys!(value, &block)
    end
    object
  when Array
    object.map! { |item| deep_transform_keys!(item, &block) }
  else
    object
  end
end

#snake_to_camel(hash) ⇒ Object



26
27
28
29
30
# File 'lib/ai21/helper.rb', line 26

def snake_to_camel(hash)
  deep_transform_keys!(hash) do |key|
    key.to_s.gsub(/(?:_|(\/))([a-z\d]*)/) { "#{$1}#{$2.capitalize}" }.to_sym
  end
end