Skip to content
Browse files

AS guide: documents Hash#to_xml

  • Loading branch information...
1 parent 5cc55dd commit d9ac4a7717007474ace12500fd91485e294e10ff @fxn fxn committed
Showing with 45 additions and 1 deletion.
  1. +45 −1 railties/guides/source/active_support_overview.textile
View
46 railties/guides/source/active_support_overview.textile
@@ -1064,7 +1064,51 @@ NOTE: Observe in the previous example that consecutive separators result in empt
h3. Extensions to +Hash+
-...
+h4. Conversions
+
+h5. +to_xml+
+
+The method +to_xml+ returns a string containing an XML representation of its receiver:
+
+<ruby>
+{"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>
+</ruby>
+
+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 with +key+ as <tt>:root</tt>.
+
+* If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>, and +key+ singularized as <tt>:children</tt>.
+
+* If +value+ is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the +options+ hash as first argument with +key+ as <tt>:root</tt>, and +key+ singularized as second argument. Its return value becomes a new node.
+
+* If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.
+
+* Otherwise, a node with +key+ as tag is created with a string representation of +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. Unless the option <tt>:skip_types</tt> exists and is true, an attribute "type" is added as well according to the following mapping:
+<ruby>
+XML_TYPE_NAMES = {
+ "Symbol" => "symbol",
+ "Fixnum" => "integer",
+ "Bignum" => "integer",
+ "BigDecimal" => "decimal",
+ "Float" => "float",
+ "TrueClass" => "boolean",
+ "FalseClass" => "boolean",
+ "Date" => "date",
+ "DateTime" => "datetime",
+ "Time" => "datetime"
+}
+</ruby>
+
+By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.
+
+The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder with the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.
h3. Extensions to +Range+

0 comments on commit d9ac4a7

Please sign in to comment.
Something went wrong with that request. Please try again.