Class: XmlFu::Array

Inherits:
Object
  • Object
show all
Defined in:
lib/xml-fu/array.rb

Overview

Convert Array to XML String

Defined Under Namespace

Classes: MissingKeyException

Class Method Summary collapse

Class Method Details

.each_with_xml(arr, opts = {}) ⇒ Object

Convenience function to iterate over array items as well as providing a single location for logic



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/xml-fu/array.rb', line 48

def self.each_with_xml(arr, opts={})
  xml = XmlFu::Markup.new(opts)

  arr.each do |item|
    key = opts.fetch(:key, "")
    item_content = item

    # Attributes reuires duplicate or child elements will
    # contain attributes of their siblings.
    attributes = (opts[:attributes] ? opts[:attributes].dup : {})

    if item.respond_to?(:keys)
      filtered = Hash.filter(item)
      item_content, attributes = filtered.first, filtered.last
    end

    item_name = ( Symbol === key ?
                 XmlFu.config.symbol_conversion_algorithm.call(key) :
                 key.to_s )

    yield xml, item_name, item_content, attributes
  end

  xml.target!
end

.to_xml(array, options = {}) ⇒ Object

Convert Array to XML String of sibling XML nodes

Options Hash (options):

  • :content_type (String)

    Either “collection” or “content”. (defaults to “content”)

  • :key (String, Symbol)

    Name of node.

  • :attributes (Hash)

    Possible hash of attributes to assign to nodes in array.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/xml-fu/array.rb', line 20

def self.to_xml(array, options={})
  each_with_xml(array, options) do |xml, key, item, attributes|
    case options[:content_type].to_s
    when "collection"
      raise(MissingKeyException, "Key name missing for collection") if key.empty?

      case item
      when ::Array then
        xml << Array.to_xml(item.flatten,options)
      else
        xml << Node.new(key, item, attributes).to_xml
      end
    else
      # Array is content of node rather than collection of node elements
      if XmlFu.recognized_object?(item)
        xml << XmlFu.xml(item, options)
      else
        # unknown xml transformation
      end
    end
  end
end