Module: Micro::Attributes::Utils::Hashes

Defined in:
lib/micro/attributes/utils.rb

Class Method Summary collapse

Class Method Details

.get(hash, key) ⇒ Object



33
34
35
36
37
# File 'lib/micro/attributes/utils.rb', line 33

def self.get(hash, key)
  value = hash[key.to_s]

  value.nil? ? hash[key.to_sym] : value
end

.keys_as(type, hash) ⇒ Object

Raises:

  • (ArgumentError)


24
25
26
27
28
29
30
31
# File 'lib/micro/attributes/utils.rb', line 24

def self.keys_as(type, hash)
  return Kind::Of.(::Hash, hash) unless type

  return symbolize_keys(hash) if type == Symbol
  return stringify_keys(hash) if type == String

  raise ArgumentError, 'first argument must be the class String or Symbol'.freeze
end

.stringify_keys(arg) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/micro/attributes/utils.rb', line 6

def self.stringify_keys(arg)
  hash = Kind::Of.(::Hash, arg)

  return hash if hash.empty?
  return hash.transform_keys(&:to_s) if hash.respond_to?(:transform_keys)

  hash.each_with_object({}) { |(key, val), memo| memo[key.to_s] = val }
end

.symbolize_keys(arg) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/micro/attributes/utils.rb', line 15

def self.symbolize_keys(arg)
  hash = Kind::Of.(::Hash, arg)

  return hash if hash.empty?
  return hash.transform_keys(&:to_sym) if hash.respond_to?(:transform_keys)

  hash.each_with_object({}) { |(key, val), memo| memo[key.to_sym] = val }
end