class Hash
def _deep_transform_keys_in_object(object, &block)
def _deep_transform_keys_in_object(object, &block) case object when Hash object.each_with_object(self.class.new) do |(key, value), result| result[yield(key)] = _deep_transform_keys_in_object(value, &block) end when Array object.map { |e| _deep_transform_keys_in_object(e, &block) } else object end end
def _deep_transform_keys_in_object!(object, &block)
def _deep_transform_keys_in_object!(object, &block) case object when Hash object.keys.each do |key| value = object.delete(key) object[yield(key)] = _deep_transform_keys_in_object!(value, &block) end object when Array object.map! { |e| _deep_transform_keys_in_object!(e, &block) } else object end end
def _deep_transform_values_in_object(object, &block)
def _deep_transform_values_in_object(object, &block) case object when Hash object.transform_values { |value| _deep_transform_values_in_object(value, &block) } when Array object.map { |e| _deep_transform_values_in_object(e, &block) } else yield(object) end end
def _deep_transform_values_in_object!(object, &block)
def _deep_transform_values_in_object!(object, &block) case object when Hash object.transform_values! { |value| _deep_transform_values_in_object!(value, &block) } when Array object.map! { |e| _deep_transform_values_in_object!(e, &block) } else yield(object) end end
def as_json(options = nil) # :nodoc:
def as_json(options = nil) # :nodoc: # create a subset of the hash by applying :only or :except subset = if options if attrs = options[:only] slice(*Array(attrs)) elsif attrs = options[:except] except(*Array(attrs)) else self end else self end result = {} if options options = options.dup.freeze unless options.frozen? subset.each { |k, v| result[k.to_s] = v.as_json(options) } else subset.each { |k, v| result[k.to_s] = v.as_json } end result end
def assert_valid_keys(*valid_keys)
{ name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'"
{ name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age"
meaning that string and symbol keys will not match.
Note that keys are treated differently than HashWithIndifferentAccess,
+ArgumentError+ on a mismatch.
Validates all keys in a hash match *valid_keys, raising
def assert_valid_keys(*valid_keys) valid_keys.flatten! each_key do |k| unless valid_keys.include?(k) raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}") end end end
def compact_blank # :nodoc:
Hash#reject has its own definition, so this needs one too.
def compact_blank # :nodoc: reject { |_k, v| v.blank? } end
def compact_blank!
h.compact_blank!
h = { a: "", b: 1, c: nil, d: [], e: false, f: true }
Uses Object#blank? for determining if a value is blank.
Removes all blank values from the +Hash+ in place and returns self.
def compact_blank! # use delete_if rather than reject! because it always returns self even if nothing changed delete_if { |_k, v| v.blank? } end
def deep_dup
hash[:a][:c] # => nil
dup[:a][:c] = 'c'
dup = hash.deep_dup
hash = { a: { b: 'b' } }
Returns a deep copy of hash.
def deep_dup hash = dup each_pair do |key, value| if ::String === key || ::Symbol === key hash[key] = value.deep_dup else hash.delete(key) hash[key.deep_dup] = value.deep_dup end end hash end
def deep_merge?(other) # :nodoc:
#
def deep_merge?(other) # :nodoc: other.is_a?(Hash) end
def deep_stringify_keys
hash.deep_stringify_keys
hash = { person: { name: 'Rob', age: '28' } }
nested hashes and arrays.
This includes the keys from the root hash and from all
Returns a new hash with all keys converted to strings.
def deep_stringify_keys deep_transform_keys { |k| Symbol === k ? k.name : k.to_s } end
def deep_stringify_keys!
This includes the keys from the root hash and from all
Destructively converts all keys to strings.
def deep_stringify_keys! deep_transform_keys! { |k| Symbol === k ? k.name : k.to_s } end
def deep_symbolize_keys
hash.deep_symbolize_keys
hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } }
and from all nested hashes and arrays.
they respond to +to_sym+. This includes the keys from the root hash
Returns a new hash with all keys converted to symbols, as long as
def deep_symbolize_keys deep_transform_keys { |key| key.to_sym rescue key } end
def deep_symbolize_keys!
to +to_sym+. This includes the keys from the root hash and from all
Destructively converts all keys to symbols, as long as they respond
def deep_symbolize_keys! deep_transform_keys! { |key| key.to_sym rescue key } end
def deep_transform_keys(&block)
hash.deep_transform_keys{ |key| key.to_s.upcase }
hash = { person: { name: 'Rob', age: '28' } }
nested hashes and arrays.
This includes the keys from the root hash and from all
Returns a new hash with all keys converted by the block operation.
def deep_transform_keys(&block) _deep_transform_keys_in_object(self, &block) end
def deep_transform_keys!(&block)
This includes the keys from the root hash and from all
Destructively converts all keys by using the block operation.
def deep_transform_keys!(&block) _deep_transform_keys_in_object!(self, &block) end
def deep_transform_values(&block)
hash.deep_transform_values{ |value| value.to_s.upcase }
hash = { person: { name: 'Rob', age: '28' } }
nested hashes and arrays.
This includes the values from the root hash and from all
Returns a new hash with all values converted by the block operation.
def deep_transform_values(&block) _deep_transform_values_in_object(self, &block) end
def deep_transform_values!(&block)
This includes the values from the root hash and from all
Destructively converts all values by using the block operation.
def deep_transform_values!(&block) _deep_transform_values_in_object!(self, &block) end
def except!(*keys)
hash.except!(:c) # => { a: true, b: false }
hash = { a: true, b: false, c: nil }
Removes the given keys from hash and returns it.
def except!(*keys) keys.each { |key| delete(key) } self end
def extract!(*keys)
hash.extract!(:a, :b) # => {:a=>1, :b=>2}
hash = { a: 1, b: 2, c: 3, d: 4 }
Removes and returns the key/value pairs matching the given keys.
def extract!(*keys) keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) } end
def extractable_options?
is extractable, Array#extract_options! pops it from
true to declare themselves as extractable. If a Hash
Subclasses of Hash may implement this method and return
By default, only instances of Hash itself are extractable.
def extractable_options? instance_of?(Hash) end
def from_trusted_xml(xml)
def from_trusted_xml(xml) from_xml xml, [] end
def from_xml(xml, disallowed_types = nil)
Note that passing custom disallowed types will override the default types,
# => ActiveSupport::XMLConverter::DisallowedType: Disallowed type attribute: "integer"
hash = Hash.from_xml(xml, ['integer'])
XML
xml = <<-XML
array.
Custom +disallowed_types+ can also be passed in the form of an
parse this XML.
type="symbol". Use Hash.from_trusted_xml to
+DisallowedType+ is raised if the XML contains attributes with type="yaml" or
# => {"hash"=>{"foo"=>1, "bar"=>2}}
hash = Hash.from_xml(xml)
XML
xml = <<-XML
its content
Returns a Hash containing a collection of pairs when the key is the node name and the value is
def from_xml(xml, disallowed_types = nil) ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h end
def present? # :nodoc:
def present? # :nodoc: !empty? end
def reverse_merge(other_hash)
This is particularly useful for initializing an options hash
options = { size: 25, velocity: 10 }.merge(options)
is equivalent to
options = options.reverse_merge(size: 25, velocity: 10)
Merges the caller into +other_hash+. For example,
def reverse_merge(other_hash) other_hash.merge(self) end
def reverse_merge!(other_hash)
def reverse_merge!(other_hash) replace(reverse_merge(other_hash)) end
def slice!(*keys)
hash.slice!(:a, :b) # => {:c=>3, :d=>4}
hash = { a: 1, b: 2, c: 3, d: 4 }
Returns a hash containing the removed key/value pairs.
Replaces the hash with only the given keys.
def slice!(*keys) omit = slice(*self.keys - keys) hash = slice(*keys) hash.default = default hash.default_proc = default_proc if default_proc replace(hash) omit end
def stringify_keys
hash.stringify_keys
hash = { name: 'Rob', age: '28' }
Returns a new hash with all keys converted to strings.
def stringify_keys transform_keys { |k| Symbol === k ? k.name : k.to_s } end
def stringify_keys!
Destructively converts all keys to strings. Same as
def stringify_keys! transform_keys! { |k| Symbol === k ? k.name : k.to_s } end
def symbolize_keys
hash.symbolize_keys
hash = { 'name' => 'Rob', 'age' => '28' }
they respond to +to_sym+.
Returns a new hash with all keys converted to symbols, as long as
def symbolize_keys transform_keys { |key| key.to_sym rescue key } end
def symbolize_keys!
Destructively converts all keys to symbols, as long as they respond
def symbolize_keys! transform_keys! { |key| key.to_sym rescue key } end
def to_query(namespace = nil)
The string pairs "key=value" that conform the query string
# => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
{name: 'David', nationality: 'Danish'}.to_query('user')
An optional namespace can be passed to enclose key names:
# => "name=David&nationality=Danish"
{name: 'David', nationality: 'Danish'}.to_query
query string:
Returns a string representation of the receiver suitable for use as a URL
def to_query(namespace = nil) query = filter_map do |key, value| unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty? value.to_query(namespace ? "#{namespace}[#{key}]" : key) end end query.sort! unless namespace.to_s.include?("[]") query.join("&") end
def to_xml(options = {})
configure your own builder with the :builder option. The method also accepts
The default XML builder is a fresh instance of +Builder::XmlMarkup+. You can
By default the root node is "hash", but that's configurable via the :root option.
}
"Time" => "dateTime"
"DateTime" => "dateTime",
"Date" => "date",
"FalseClass" => "boolean",
"TrueClass" => "boolean",
"Float" => "float",
"BigDecimal" => "decimal",
"Integer" => "integer",
"Symbol" => "symbol",
XML_TYPE_NAMES = {
added as well according to the following mapping:
Unless the option :skip_types exists and is true, an attribute "type" is
+value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added.
* Otherwise, a node with +key+ as tag is created with a string representation of
#
#
#
# =>
{ foo: Foo.new }.to_xml(skip_instruct: true)
end
end
options[:builder].bar 'fooing!'
def to_xml(options)
class Foo
* If +value+ responds to +to_xml+ the method is invoked with +key+ as :root.
# => "foo"
{foo: lambda { |options, key| options[:builder].b(key) }}.to_xml
callable can add nodes by using options[:builder].
with +key+ as :root, and +key+ singularized as second argument. The
on the arity, the callable is invoked with the +options+ hash as first argument
* If +value+ is a callable object it must expect one or two arguments. Depending
and +key+ singularized as :children.
* If +value+ is an array there's a recursive call with +key+ as :root,
* If +value+ is a hash there's a recursive call with +key+ as :root.
the _values_. Given a pair +key+, +value+:
To do so, the method loops over the pairs and builds nodes that depend on
#
#
#
#
#
# =>
{ foo: 1, bar: 2 }.to_xml
Returns a string containing an XML representation of its receiver:
def to_xml(options = {}) require "active_support/builder" unless defined?(Builder::XmlMarkup) options = options.dup options[:indent] ||= 2 options[:root] ||= "hash" options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent]) builder = options[:builder] builder.instruct! unless options.delete(:skip_instruct) root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options) builder.tag!(root) do each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) } yield builder if block_given? end end
def with_indifferent_access
Returns an ActiveSupport::HashWithIndifferentAccess out of its receiver:
def with_indifferent_access ActiveSupport::HashWithIndifferentAccess.new(self) end