Class: Hash

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

Overview

:nodoc:

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.hash_traverse(hash, &block) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/webmaster/core_ext/hash.rb', line 71

def self.hash_traverse(hash, &block)
  hash.each do |key, val|
    block.call(key)
    case val
    when Hash
      val.keys.each do |k|
        _hash_traverse(val, &block)
      end
    when Array
      val.each do |item|
        _hash_traverse(item, &block)
      end
    end
  end
  return hash
end

Instance Method Details

#all_keysObject

:nodoc:



56
57
58
59
60
61
62
63
64
65
# File 'lib/webmaster/core_ext/hash.rb', line 56

def all_keys # :nodoc:
  keys = self.keys
  keys.each do |key|
    if self[key].is_a?(Hash)
      keys << self[key].all_keys.compact.flatten
      next
    end
  end
  keys.flatten
end

#except(*items) ⇒ Object

:nodoc:



3
4
5
# File 'lib/webmaster/core_ext/hash.rb', line 3

def except(*items) # :nodoc:
  self.dup.except!(*items)
end

#except!(*keys) ⇒ Object

:nodoc:



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

def except!(*keys) # :nodoc:
  copy = self.dup
  keys.each { |key| copy.delete!(key) }
  copy
end

#has_deep_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/webmaster/core_ext/hash.rb', line 67

def has_deep_key?(key)
  self.all_keys.include? key
end

#serializeObject

:nodoc:



52
53
54
# File 'lib/webmaster/core_ext/hash.rb', line 52

def serialize # :nodoc:
  self.map { |key, val| [key, val].join("=") }.join("&")
end

#slice(*keys) ⇒ Object



13
14
15
16
17
18
# File 'lib/webmaster/core_ext/hash.rb', line 13

def slice(*keys)
  keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
  hash = self.class.new
  keys.each { |k| hash[k] = self[k] if has_key?(k) }
  hash
end

#slice!(*keys) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/webmaster/core_ext/hash.rb', line 20

def slice!(*keys)
  keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true)
  omit = slice(*self.keys - keys)
  hash = slice(*keys)
  replace(hash)
  omit
end

#symbolize_keysObject

:nodoc:



28
29
30
31
32
33
# File 'lib/webmaster/core_ext/hash.rb', line 28

def symbolize_keys  # :nodoc:
  inject({}) do |hash, (key, value)|
    hash[(key.to_sym rescue key) || key] = value
    hash
  end
end

#symbolize_keys!Object

:nodoc:



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/webmaster/core_ext/hash.rb', line 35

def symbolize_keys! # :nodoc:
  hash = symbolize_keys
  hash.each do |key, val|
    hash[key] = case val
      when Hash
        val.symbolize_keys!
      when Array
        val.map do |item|
          item.is_a?(Hash) ? item.symbolize_keys! : item
        end
      else
        val
      end
  end
  return hash
end