Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/hash.rb

Overview

Help us deal with hashes with various key shapes/types

Instance Method Summary collapse

Instance Method Details

#redoxify_keysObject

transform camel_case (symbol) keys to RedoxCase string keys



32
33
34
35
36
37
38
39
40
# File 'lib/core_ext/hash.rb', line 32

def redoxify_keys
  transform_keys do |key|
    key = key[0..-1]
    next 'IDType' if %w[id_type IDType].include? key
    next key if key =~ /^([A-Z]{1}[a-z]+)+/
    next key.upcase if key =~ /^[A-Za-z]{2,3}$/
    key.split('_').map(&:capitalize).join
  end
end

#rubyize_keysObject

transform RedoxCase string keys to ruby symbol keys



43
44
45
46
47
48
49
50
51
52
# File 'lib/core_ext/hash.rb', line 43

def rubyize_keys
  transform_keys do |key|
    key
      .to_s
      .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
      .gsub(/([a-z\d])([A-Z])/, '\1_\2')
      .downcase
      .to_sym
  end
end

#symbolize_keysObject

Rails method, find at activesupport/lib/active_support/core_ext/hash/keys.rb, line 50



27
28
29
# File 'lib/core_ext/hash.rb', line 27

def symbolize_keys
  transform_keys { |key| key.to_sym rescue key }
end

#transform_keys(&block) ⇒ Object

recursively transform keys/values according to a given block



4
5
6
7
8
9
10
11
# File 'lib/core_ext/hash.rb', line 4

def transform_keys(&block)
  map do |key, value|
    [
      yield(key),
      transform_value(value, &block)
    ]
  end.to_h
end

#transform_value(value, &block) ⇒ Object

recursively transform values that contain a data structure, return the value if it isn’t a hash



15
16
17
18
19
20
21
22
23
# File 'lib/core_ext/hash.rb', line 15

def transform_value(value, &block)
  if value.respond_to?(:each_index)
    value.map do |elem|
      elem.transform_keys(&block) rescue elem
    end
  else
    value.transform_keys(&block) rescue value
  end
end