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

Extended by:
Hashes
Included in:
Hashes
Defined in:
lib/micro/attributes/utils.rb

Instance Method Summary collapse

Instance Method Details

#assoc(hash, key) ⇒ Object



35
36
37
38
39
# File 'lib/micro/attributes/utils.rb', line 35

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

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

#keys_as(type, hash) ⇒ Object

Raises:

  • (ArgumentError)


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

def keys_as(type, hash)
  return Kind::Hash[hash] unless type

  return symbolize_keys(hash) if type == Symbol || type == :symbol
  return stringify_keys(hash) if type == String || type == :string

  raise ArgumentError, 'argument must be one of these values: :symbol, :string, Symbol, String'.freeze
end

#stringify_keys(arg) ⇒ Object



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

def stringify_keys(arg)
  hash = Kind::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



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

def symbolize_keys(arg)
  hash = Kind::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