Class: Hash

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

Direct Known Subclasses

Videojuicer::Resource::Errors

Instance Method Summary collapse

Instance Method Details

#deep_merge(hash) ⇒ Object

Merges self with another hash, recursively.

This code was lovingly stolen from some random gem: gemjack.com/gems/tartan-0.1.1/classes/Hash.html

Thanks to whoever made it.



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/core_ext/hash.rb', line 33

def deep_merge(hash)
  target = dup
  
  hash.keys.each do |key|
    if hash[key].is_a? Hash and self[key].is_a? Hash
      target[key] = target[key].deep_merge(hash[key])
      next
    end      
    target[key] = hash[key]
  end    
  target
end

#deep_stringifyObject

Returns a new hash just like this one, but with all the symbol keys expressed as strings. Also applies to hashes within self. Based on an implementation within Rails 2.x, thanks Rails!



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

def deep_stringify
  target = dup
  target.inject({}) do |memo, (key, value)|
    value = value.deep_stringify if value.is_a?(Hash)
    memo[(key.to_s rescue key) || key] = value
    memo
  end
end

#deep_symbolizeObject

Returns a new hash just like this one, but with all the string keys expressed as symbols. Also applies to hashes within self. Based on an implementation within Rails 2.x, thanks Rails!



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

def deep_symbolize
  target = dup    
  target.inject({}) do |memo, (key, value)|
    value = value.deep_symbolize if value.is_a?(Hash)
    memo[(key.to_sym rescue key) || key] = value
    memo
  end
end

#to_xmlObject



46
47
48
49
50
# File 'lib/core_ext/hash.rb', line 46

def to_xml
  inject("") do |memo, (key, value)|
    memo << "<#{key}>#{(value.respond_to?(:to_xml))? value.to_xml : value}</#{key}>"
  end
end