instance method
to_xml
Ruby on Rails 4.2.9
Since v3.0.20Signature
to_xml(options = {})
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
valueis a hash there’s a recursive call withkeyas:root. -
If
valueis an array there’s a recursive call withkeyas:root, andkeysingularized as:children. -
If
valueis a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with theoptionshash as first argument withkeyas:root, andkeysingularized as second argument. The callable can add nodes by usingoptions[:builder].'foo'.to_xml(lambda { |options, key| options[:builder].b(key) }) # => "<b>foo</b>"
-
If
valueresponds toto_xmlthe method is invoked withkeyas:root.class Foo def to_xml(options) options[:builder].bar 'fooing!' end end { foo: Foo.new }.to_xml(skip_instruct: true) # => # <hash> # <bar>fooing!</bar> # </hash>
-
Otherwise, a node with
keyas tag is created with a string representation ofvalueas text node. Ifvalueisnilan attribute “nil” set to “true” is added. Unless the option:skip_typesexists and is true, an attribute “type” is added as well according to the following mapping:XML_TYPE_NAMES = { "Symbol" => "symbol", "Integer" => "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.
Parameters
-
optionsopt = {}
Source
# File activesupport/lib/active_support/core_ext/hash/conversions.rb, line 73
def to_xml(options = {})
require 'active_support/builder' unless defined?(Builder)
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
Defined in activesupport/lib/active_support/core_ext/hash/conversions.rb line 73
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Hash