Class: TropoRest::Utils

Inherits:
Object
  • Object
show all
Defined in:
lib/tropo_rest/utils.rb

Overview

Utilities

Class Method Summary collapse

Class Method Details

.camelize(hash) ⇒ Object

Convert hash keys from underscore to camel case



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/tropo_rest/utils.rb', line 20

def self.camelize(hash)
  dup = hash.dup
  dup.keys.each do |k|
    value = dup.delete(k)
    key = k.to_s.dup
    if key =~ /_/
      key = key[0].chr.downcase + key.gsub(/(?:^|_)(.)/) { $1.upcase }[1..-1]
    end
    dup[key] = value
  end
  dup
end

.underscore(hash) ⇒ Object

Convert hash keys from camel case to underscore



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

def self.underscore(hash)
  dup = hash.dup
  dup.keys.select { |k| k =~ /[A-Z]/ }.each do |k|
    value = dup.delete(k)
    key = k.dup
    key.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
    key.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
    key.tr!("-", "_")
    key.downcase!
    dup[key] = value
  end
  dup
end