Module: Miu::Utility

Defined in:
lib/miu/utility.rb

Class Method Summary collapse

Class Method Details

.adapt(klass, value) ⇒ Object



5
6
7
8
# File 'lib/miu/utility.rb', line 5

def adapt(klass, value)
  value ||= {}
  value.is_a?(klass) ? value : klass.new(value)
end

.extract_options!(args) ⇒ Object



10
11
12
# File 'lib/miu/utility.rb', line 10

def extract_options!(args)
  args.last.is_a?(::Hash) ? args.pop : {}
end

.modify_keys(hash, recursive = false, &block) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/miu/utility.rb', line 14

def modify_keys(hash, recursive = false, &block)
  hash = hash.dup
  if block
    hash.keys.each do |key|
      value = hash.delete(key)
      if recursive
        case value
        when ::Hash
          value = modify_keys(value, recursive, &block)
        when ::Array
          value = value.map { |v| v.is_a?(::Hash) ? modify_keys(v, recursive, &block) : v }
        end
      end
      key = block.call key
      hash[key] = value
    end
  end
  hash
end

.optionify_keys(hash, recursive = false) ⇒ Object



46
47
48
49
50
# File 'lib/miu/utility.rb', line 46

def optionify_keys(hash, recursive = false)
  modify_keys(hash, recursive) do |key|
    key.to_s.gsub('-', '_').to_sym rescue key
  end
end

.symbolize_keys(hash, recursive = false) ⇒ Object



34
35
36
37
38
# File 'lib/miu/utility.rb', line 34

def symbolize_keys(hash, recursive = false)
  modify_keys(hash, recursive) do |key|
    key.to_sym rescue key
  end
end

.underscorize_keys(hash, recursive = false) ⇒ Object



40
41
42
43
44
# File 'lib/miu/utility.rb', line 40

def underscorize_keys(hash, recursive = false)
  modify_keys(hash, recursive) do |key|
    key.gsub('-', '_') rescue key
  end
end