Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/activerecord_clone.rb
Instance Method Summary collapse
-
#deep_merge(hash) ⇒ Object
Merges self with another hash, recursively.
-
#deep_merge!(second) ⇒ Object
From: www.gemtacular.com/gemdocs/cerberus-0.2.2/doc/classes/Hash.html File lib/cerberus/utils.rb, line 42.
-
#deep_merge2(other) ⇒ Object
cf.
- #deep_merge3(second) ⇒ Object
- #keep_merge(hash) ⇒ Object
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.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/activerecord_clone.rb', line 10 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_merge!(second) ⇒ Object
From: www.gemtacular.com/gemdocs/cerberus-0.2.2/doc/classes/Hash.html File lib/cerberus/utils.rb, line 42
29 30 31 32 33 34 35 36 37 |
# File 'lib/activerecord_clone.rb', line 29 def deep_merge!(second) second.each_pair do |k,v| if self[k].is_a?(Hash) and second[k].is_a?(Hash) self[k].deep_merge!(second[k]) else self[k] = second[k] end end end |
#deep_merge2(other) ⇒ Object
43 44 45 46 47 48 49 50 51 |
# File 'lib/activerecord_clone.rb', line 43 def deep_merge2(other) deep_proc = Proc.new { |k, s, o| if s.kind_of?(Hash) && o.kind_of?(Hash) next s.merge(o, &deep_proc) end next o } merge(other, &deep_proc) end |
#deep_merge3(second) ⇒ Object
54 55 56 57 58 59 60 61 62 |
# File 'lib/activerecord_clone.rb', line 54 def deep_merge3(second) # From: http://www.ruby-forum.com/topic/142809 # Author: Stefan Rusterholz merger = proc { |key,v1,v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } self.merge(second, &merger) end |
#keep_merge(hash) ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/activerecord_clone.rb', line 65 def keep_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].keep_merge(hash[key]) next end #target[key] = hash[key] target.update(hash) { |key, *values| values.flatten.uniq } end target end |