1 module ActiveSupport
#:nodoc:
2 module CoreExtensions
#:nodoc:
4 # Slice a hash to include only the given keys. This is useful for
5 # limiting an options hash to valid keys before passing to a method:
7 # def search(criteria = {})
8 # assert_valid_keys(:mass, :velocity, :time)
11 # search(options.slice(:mass, :velocity, :time))
13 # If you have an array of keys you want to limit to, you should splat them:
15 # valid_keys = [:mass, :velocity, :time]
16 # search(options.slice(*valid_keys))
18 # Returns a new hash with only the given keys.
20 keys
= keys
.map
! { |key
| convert_key(key
) } if respond_to
?(:convert_key)
22 keys
.each
{ |k
| hash
[k
] = self[k
] if has_key
?(k
) }
26 # Replaces the hash with only the given keys.
27 # Returns a hash contained the removed key/value pairs
28 # {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d =>4}
30 keys
= keys
.map
! { |key
| convert_key(key
) } if respond_to
?(:convert_key)
31 omit
= slice(*self.keys
- keys
)