OSDN Git Service

546e261cc90e8f59080e1d0b0f9286a15a157847
[redminele/redminele.git] / ruby / lib / ruby / gems / 1.8 / gems / activesupport-2.3.5 / lib / active_support / core_ext / hash / reverse_merge.rb
1 module ActiveSupport #:nodoc:
2   module CoreExtensions #:nodoc:
3     module Hash #:nodoc:
4       # Allows for reverse merging two hashes where the keys in the calling hash take precedence over those
5       # in the <tt>other_hash</tt>. This is particularly useful for initializing an option hash with default values:
6       #
7       #   def setup(options = {})
8       #     options.reverse_merge! :size => 25, :velocity => 10
9       #   end
10       #
11       # Using <tt>merge</tt>, the above example would look as follows:
12       #
13       #   def setup(options = {})
14       #     { :size => 25, :velocity => 10 }.merge(options)
15       #   end
16       #
17       # The default <tt>:size</tt> and <tt>:velocity</tt> are only set if the +options+ hash passed in doesn't already
18       # have the respective key.
19       module ReverseMerge
20         # Performs the opposite of <tt>merge</tt>, with the keys and values from the first hash taking precedence over the second.
21         def reverse_merge(other_hash)
22           other_hash.merge(self)
23         end
24
25         # Performs the opposite of <tt>merge</tt>, with the keys and values from the first hash taking precedence over the second.
26         # Modifies the receiver in place.
27         def reverse_merge!(other_hash)
28           replace(reverse_merge(other_hash))
29         end
30
31         alias_method :reverse_update, :reverse_merge!
32       end
33     end
34   end
35 end