Class: Hash
- Defined in:
- lib/active_support/core_ext/object/blank.rb,
lib/active_support/json/encoding.rb,
lib/active_support/core_ext/hash/diff.rb,
lib/active_support/core_ext/hash/keys.rb,
lib/active_support/core_ext/hash/slice.rb,
lib/active_support/core_ext/hash/except.rb,
lib/active_support/core_ext/hash/deep_merge.rb,
lib/active_support/core_ext/object/to_param.rb,
lib/active_support/core_ext/object/to_query.rb,
lib/active_support/core_ext/hash/conversions.rb,
lib/active_support/core_ext/hash/reverse_merge.rb,
lib/active_support/core_ext/array/extract_options.rb,
lib/active_support/core_ext/hash/indifferent_access.rb
Overview
:nodoc:
Direct Known Subclasses
ActiveSupport::Dependencies::WatchStack, ActiveSupport::HashWithIndifferentAccess, ActiveSupport::OrderedHash
Class Method Summary collapse
Instance Method Summary collapse
-
#as_json(options = nil) ⇒ Object
:nodoc:.
-
#assert_valid_keys(*valid_keys) ⇒ Object
Validate all keys in a hash match *valid keys, raising ArgumentError on a mismatch.
-
#deep_merge(other_hash) ⇒ Object
Returns a new hash with
self
andother_hash
merged recursively. -
#deep_merge!(other_hash) ⇒ Object
Returns a new hash with
self
andother_hash
merged recursively. -
#diff(h2) ⇒ Object
Returns a hash that represents the difference between two hashes.
- #encode_json(encoder) ⇒ Object
-
#except(*keys) ⇒ Object
Return a hash that includes everything but the given keys.
-
#except!(*keys) ⇒ Object
Replaces the hash without the given keys.
- #extract!(*keys) ⇒ Object
-
#extractable_options? ⇒ Boolean
By default, only instances of Hash itself are extractable.
-
#reverse_merge(other_hash) ⇒ Object
Allows for reverse merging two hashes where the keys in the calling hash take precedence over those in the
other_hash
. -
#reverse_merge!(other_hash) ⇒ Object
(also: #reverse_update)
Performs the opposite of
merge
, with the keys and values from the first hash taking precedence over the second. -
#slice(*keys) ⇒ Object
Slice a hash to include only the given keys.
-
#slice!(*keys) ⇒ Object
Replaces the hash with only the given keys.
-
#stringify_keys ⇒ Object
Return a new hash with all keys converted to strings.
-
#stringify_keys! ⇒ Object
Destructively convert all keys to strings.
-
#symbolize_keys ⇒ Object
(also: #to_options)
Return a new hash with all keys converted to symbols, as long as they respond to
to_sym
. -
#symbolize_keys! ⇒ Object
(also: #to_options!)
Destructively convert all keys to symbols, as long as they respond to
to_sym
. -
#to_param(namespace = nil) ⇒ Object
(also: #to_query)
Converts a hash into a string suitable for use as a URL query string.
-
#to_xml(options = {}) ⇒ Object
Returns a string containing an XML representation of its receiver:.
-
#with_indifferent_access ⇒ Object
Returns an
ActiveSupport::HashWithIndifferentAccess
out of its receiver:.
Class Method Details
.from_xml(xml) ⇒ Object
77 78 79 |
# File 'lib/active_support/core_ext/hash/conversions.rb', line 77 def from_xml(xml) typecast_xml_value(unrename_keys(ActiveSupport::XmlMini.parse(xml))) end |
Instance Method Details
#as_json(options = nil) ⇒ Object
:nodoc:
194 195 196 197 198 199 200 201 202 203 204 205 206 |
# File 'lib/active_support/json/encoding.rb', line 194 def as_json( = nil) #:nodoc: if if attrs = [:only] slice(*Array.wrap(attrs)) elsif attrs = [:except] except(*Array.wrap(attrs)) else self end else self end end |
#assert_valid_keys(*valid_keys) ⇒ Object
Validate all keys in a hash match *valid keys, raising ArgumentError on a mismatch. Note that keys are NOT treated indifferently, meaning if you use strings for keys but assert symbols as keys, this will fail.
Examples
{ :name => "Rob", :years => "28" }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key(s): years"
{ :name => "Rob", :age => "28" }.assert_valid_keys("name", "age") # => raises "ArgumentError: Unknown key(s): name, age"
{ :name => "Rob", :age => "28" }.assert_valid_keys(:name, :age) # => passes, raises nothing
41 42 43 44 |
# File 'lib/active_support/core_ext/hash/keys.rb', line 41 def assert_valid_keys(*valid_keys) unknown_keys = keys - [valid_keys].flatten raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? end |
#deep_merge(other_hash) ⇒ Object
Returns a new hash with self
and other_hash
merged recursively.
3 4 5 |
# File 'lib/active_support/core_ext/hash/deep_merge.rb', line 3 def deep_merge(other_hash) dup.deep_merge!(other_hash) end |
#deep_merge!(other_hash) ⇒ Object
Returns a new hash with self
and other_hash
merged recursively. Modifies the receiver in place.
9 10 11 12 13 14 15 |
# File 'lib/active_support/core_ext/hash/deep_merge.rb', line 9 def deep_merge!(other_hash) other_hash.each_pair do |k,v| tv = self[k] self[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? tv.deep_merge(v) : v end self end |
#diff(h2) ⇒ Object
Returns a hash that represents the difference between two hashes.
Examples:
{1 => 2}.diff(1 => 2) # => {}
{1 => 2}.diff(1 => 3) # => {1 => 2}
{}.diff(1 => 2) # => {1 => 2}
{1 => 2, 3 => 4}.diff(1 => 2) # => {3 => 4}
10 11 12 |
# File 'lib/active_support/core_ext/hash/diff.rb', line 10 def diff(h2) dup.delete_if { |k, v| h2[k] == v }.merge!(h2.dup.delete_if { |k, v| has_key?(k) }) end |
#encode_json(encoder) ⇒ Object
208 209 210 |
# File 'lib/active_support/json/encoding.rb', line 208 def encode_json(encoder) "{#{map { |k,v| "#{encoder.encode(k.to_s)}:#{encoder.encode(v)}" } * ','}}" end |
#except(*keys) ⇒ Object
Return a hash that includes everything but the given keys. This is useful for limiting a set of parameters to everything but a few known toggles:
@person.update_attributes(params[:person].except(:admin))
If the receiver responds to convert_key
, the method is called on each of the arguments. This allows except
to play nice with hashes with indifferent access for instance:
{:a => 1}.with_indifferent_access.except(:a) # => {}
{:a => 1}.with_indifferent_access.except("a") # => {}
14 15 16 |
# File 'lib/active_support/core_ext/hash/except.rb', line 14 def except(*keys) dup.except!(*keys) end |
#except!(*keys) ⇒ Object
Replaces the hash without the given keys.
19 20 21 22 |
# File 'lib/active_support/core_ext/hash/except.rb', line 19 def except!(*keys) keys.each { |key| delete(key) } self end |
#extract!(*keys) ⇒ Object
33 34 35 36 37 |
# File 'lib/active_support/core_ext/hash/slice.rb', line 33 def extract!(*keys) result = {} keys.each {|key| result[key] = delete(key) } result end |
#extractable_options? ⇒ Boolean
By default, only instances of Hash itself are extractable. Subclasses of Hash may implement this method and return true to declare themselves as extractable. If a Hash is extractable, Array#extract_options! pops it from the Array when it is the last element of the Array.
7 8 9 |
# File 'lib/active_support/core_ext/array/extract_options.rb', line 7 def instance_of?(Hash) end |
#reverse_merge(other_hash) ⇒ Object
Allows for reverse merging two hashes where the keys in the calling hash take precedence over those in the other_hash
. This is particularly useful for initializing an option hash with default values:
def setup( = {})
.reverse_merge! :size => 25, :velocity => 10
end
Using merge
, the above example would look as follows:
def setup( = {})
{ :size => 25, :velocity => 10 }.merge()
end
The default :size
and :velocity
are only set if the options
hash passed in doesn’t already have the respective key.
17 18 19 |
# File 'lib/active_support/core_ext/hash/reverse_merge.rb', line 17 def reverse_merge(other_hash) other_hash.merge(self) end |
#reverse_merge!(other_hash) ⇒ Object Also known as: reverse_update
Performs the opposite of merge
, with the keys and values from the first hash taking precedence over the second. Modifies the receiver in place.
23 24 25 |
# File 'lib/active_support/core_ext/hash/reverse_merge.rb', line 23 def reverse_merge!(other_hash) merge!( other_hash ){|k,o,n| o } end |
#slice(*keys) ⇒ Object
Slice a hash to include only the given keys. This is useful for limiting an options hash to valid keys before passing to a method:
def search(criteria = {})
assert_valid_keys(:mass, :velocity, :time)
end
search(.slice(:mass, :velocity, :time))
If you have an array of keys you want to limit to, you should splat them:
valid_keys = [:mass, :velocity, :time]
search(.slice(*valid_keys))
15 16 17 18 19 20 |
# File 'lib/active_support/core_ext/hash/slice.rb', line 15 def slice(*keys) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) hash = self.class.new keys.each { |k| hash[k] = self[k] if has_key?(k) } hash end |
#slice!(*keys) ⇒ Object
Replaces the hash with only the given keys. Returns a hash contained the removed key/value pairs
{:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d =>4}
25 26 27 28 29 30 31 |
# File 'lib/active_support/core_ext/hash/slice.rb', line 25 def slice!(*keys) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) omit = slice(*self.keys - keys) hash = slice(*keys) replace(hash) omit end |
#stringify_keys ⇒ Object
Return a new hash with all keys converted to strings.
3 4 5 |
# File 'lib/active_support/core_ext/hash/keys.rb', line 3 def stringify_keys dup.stringify_keys! end |
#stringify_keys! ⇒ Object
Destructively convert all keys to strings.
8 9 10 11 12 13 |
# File 'lib/active_support/core_ext/hash/keys.rb', line 8 def stringify_keys! keys.each do |key| self[key.to_s] = delete(key) end self end |
#symbolize_keys ⇒ Object Also known as: to_options
Return a new hash with all keys converted to symbols, as long as they respond to to_sym
.
17 18 19 |
# File 'lib/active_support/core_ext/hash/keys.rb', line 17 def symbolize_keys dup.symbolize_keys! end |
#symbolize_keys! ⇒ Object Also known as: to_options!
Destructively convert all keys to symbols, as long as they respond to to_sym
.
23 24 25 26 27 28 |
# File 'lib/active_support/core_ext/hash/keys.rb', line 23 def symbolize_keys! keys.each do |key| self[(key.to_sym rescue key) || key] = delete(key) end self end |
#to_param(namespace = nil) ⇒ Object Also known as: to_query
Converts a hash into a string suitable for use as a URL query string. An optional namespace
can be passed to enclose the param names (see example below).
Examples
{ :name => 'David', :nationality => 'Danish' }.to_param # => "name=David&nationality=Danish"
{ :name => 'David', :nationality => 'Danish' }.to_param('user') # => "user[name]=David&user[nationality]=Danish"
44 45 46 47 48 |
# File 'lib/active_support/core_ext/object/to_param.rb', line 44 def to_param(namespace = nil) collect do |key, value| value.to_query(namespace ? "#{namespace}[#{key}]" : key) end * '&' end |
#to_xml(options = {}) ⇒ Object
Returns a string containing an XML representation of its receiver:
{"foo" => 1, "bar" => 2}.to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <hash>
# <foo type="integer">1</foo>
# <bar type="integer">2</bar>
# </hash>
To do so, the method loops over the pairs and builds nodes that depend on the values. Given a pair key
, value
:
-
If
value
is a hash there’s a recursive call withkey
as:root
. -
If
value
is an array there’s a recursive call withkey
as:root
, andkey
singularized as:children
. -
If
value
is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with theoptions
hash as first argument withkey
as:root
, andkey
singularized as second argument. Its return value becomes a new node. -
If
value
responds toto_xml
the method is invoked withkey
as:root
. -
Otherwise, a node with
key
as tag is created with a string representation ofvalue
as text node. Ifvalue
isnil
an attribute “nil” set to “true” is added. Unless the option:skip_types
exists and is true, an attribute “type” is added as well according to the following mapping:XML_TYPE_NAMES = { "Symbol" => "symbol", "Fixnum" => "integer", "Bignum" => "integer", "BigDecimal" => "decimal", "Float" => "float", "TrueClass" => "boolean", "FalseClass" => "boolean", "Date" => "date", "DateTime" => "datetime", "Time" => "datetime" }
By default the root node is “hash”, but that’s configurable via the :root
option.
The default XML builder is a fresh instance of Builder::XmlMarkup
. You can configure your own builder with the :builder
option. The method also accepts options like :dasherize
and friends, they are forwarded to the builder.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/active_support/core_ext/hash/conversions.rb', line 57 def to_xml( = {}) require 'active_support/builder' unless defined?(Builder) = .dup [:indent] ||= 2 [:root] ||= "hash" [:builder] ||= Builder::XmlMarkup.new(:indent => [:indent]) builder = [:builder] builder.instruct! unless .delete(:skip_instruct) root = ActiveSupport::XmlMini.rename_key([:root].to_s, ) builder.__send__(:method_missing, root) do each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, ) } yield builder if block_given? end end |
#with_indifferent_access ⇒ Object
Returns an ActiveSupport::HashWithIndifferentAccess
out of its receiver:
{:a => 1}.with_indifferent_access["a"] # => 1
9 10 11 |
# File 'lib/active_support/core_ext/hash/indifferent_access.rb', line 9 def with_indifferent_access ActiveSupport::HashWithIndifferentAccess.(self) end |