Class: Array
- Includes:
- Abiquo::ToXml
- Defined in:
- lib/to_xml.rb,
lib/core_ext.rb
Instance Method Summary collapse
-
#to_xml(options = {}) ⇒ Object
Returns a string that represents this array in XML by sending
to_xmlto each element.
Methods included from Abiquo::ToXml
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)
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 |
# File 'lib/core_ext.rb', line 350 def to_xml( = {}) raise "Not all elements respond to to_xml" unless all? { |e| e.respond_to? :to_xml } require 'builder' unless defined?(Builder) = .dup [:root] ||= all? { |e| e.is_a?(first.class) && first.class.to_s != "Hash" } ? first.class.to_s.underscore.pluralize.tr('/', '-') : "records" [: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 |