Module: Dhis2::Case

Defined in:
lib/dhis2/case.rb

Constant Summary collapse

SUPPORTER_CASE_CHANGES =
%i(underscore camelize).freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.camelize(string, uppercase_first_letter = true) ⇒ Object



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

def self.camelize(string, uppercase_first_letter = true)
  string = if uppercase_first_letter
             string.sub(/^[a-z\d]*/) { $&.capitalize }
           else
             string.sub(/^(?:(?=\b|[A-Z_])|\w)/) { $&.downcase }
           end
  string
    .gsub(/(?:_|(\/))([a-z\d]*)/) do
      "#{Regexp.last_match(1)}#{Regexp.last_match(2).capitalize}"
    end
    .gsub("/", "::")
end

.deep_change(obj, type) ⇒ Object

Raises:



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/dhis2/case.rb', line 7

def self.deep_change(obj, type)
  raise CaseError, deep_change_error(type) unless SUPPORTER_CASE_CHANGES.include?(type)
  case obj
  when Array then obj.map { |v| deep_change(v, type) }
  when Hash
    obj.each_with_object({}) do |(k, v), new_hash|
      new_key = type == :underscore ? underscore(k.to_s) : camelize(k.to_s, false)
      new_hash[new_key] = deep_change(v, type)
    end
  else obj
  end
end

.underscore(camel_cased_word) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/dhis2/case.rb', line 33

def self.underscore(camel_cased_word)
  return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/
  camel_cased_word.to_s.gsub(/::/, "/")
                  .gsub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
                  .gsub(/([a-z\d])([A-Z])/, '\1_\2')
                  .tr("-", "_")
                  .downcase
end

Instance Method Details

#deep_change_error(type) ⇒ Object



42
43
44
# File 'lib/dhis2/case.rb', line 42

def deep_change_error(type)
  "unsupported case changes #{type} vs #{SUPPORTER_CASE_CHANGES}"
end