Method: Array#to_xml
- Defined in:
- activesupport/lib/active_support/core_ext/array/conversions.rb
#to_xml(options = {}) ⇒ Object
Returns a string that represents the array in XML by invoking to_xml
on each element. Active Record collections delegate their representation
in XML to this method.
All elements are expected to respond to to_xml, if any of them does
not then an exception is raised.
The root node reflects the class name of the first element in plural if all elements belong to the same type and that's not Hash:
customer.projects.to_xml
Otherwise the root element is "objects":
[{ foo: 1, bar: 2}, { baz: 3}].to_xml
If the collection is empty the root element is "nil-classes" by default:
[].to_xml
To ensure a meaningful root element use the :root option:
customer_with_no_projects.projects.to_xml(root: 'projects')
By default name of the node for the children of root is root.singularize. You can change it with the :children option.
The options hash is passed downwards:
Message.all.to_xml(skip_types: true)
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
# File 'activesupport/lib/active_support/core_ext/array/conversions.rb', line 183 def to_xml( = {}) require "active_support/builder" unless defined?(Builder::XmlMarkup) = .dup [:indent] ||= 2 [:builder] ||= Builder::XmlMarkup.new(indent: [:indent]) [:root] ||= \ if first.class != Hash && all?(first.class) underscored = ActiveSupport::Inflector.underscore(first.class.name) ActiveSupport::Inflector.pluralize(underscored).tr("/", "_") else "objects" end builder = [:builder] builder.instruct! unless .delete(:skip_instruct) root = ActiveSupport::XmlMini.rename_key([:root].to_s, ) children = .delete(:children) || root.singularize attributes = [:skip_types] ? {} : { type: "array" } if empty? builder.tag!(root, attributes) else builder.tag!(root, attributes) do each { |value| ActiveSupport::XmlMini.to_tag(children, value, ) } yield builder if block_given? end end end |