Module: ActiveSupport::CoreExtensions::Array::Conversions
- Included in:
- Array
- Defined in:
- lib/active_support/core_ext/array/conversions.rb
Instance Method Summary collapse
-
#to_xml(options = {}) ⇒ Object
Returns a string that represents this array in XML by sending
to_xmlto each element.
Instance Method Details
#to_xml(options = {}) ⇒ Object
Returns a string that represents this array in XML by sending to_xml
to 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 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 "records":
[{: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 root children have as node name the one of the root singularized. You can change it with the :children option.
The options hash is passed downwards:
Message.all.to_xml(:skip_types => true)
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/active_support/core_ext/array/conversions.rb', line 83 def to_xml( = {}) raise "Not all elements respond to to_xml" unless all? { |e| e.respond_to? :to_xml } [:root] ||= all? { |e| e.is_a?(first.class) && first.class.to_s != "Hash" } ? first.class.to_s.underscore.pluralize : "objects" [:children] ||= [:root].singularize [:indent] ||= 2 [:builder] ||= Builder::XmlMarkup.new(:indent => [:indent]) root = .delete(:root).to_s children = .delete(:children) if !.has_key?(:dasherize) || [:dasherize] root = root.dasherize end [:builder].instruct! unless .delete(:skip_instruct) opts = .merge({ :root => children }) xml = [:builder] if empty? xml.tag!(root, [:skip_types] ? {} : {:type => "array"}) else xml.tag!(root, [:skip_types] ? {} : {:type => "array"}) { yield xml if block_given? each { |e| e.to_xml(opts.merge({ :skip_instruct => true })) } } end end |