Class: Resto::Format::Xml

Inherits:
Object
  • Object
show all
Extended by:
Resto::Format
Defined in:
lib/resto/format/xml.rb

Overview

Used when sending and receiveing XML data.

Class Method Summary collapse

Methods included from Resto::Format

accept, content_type, decode, encode, extension, get

Class Method Details

.acceptString

The accept header when sending XML data.

Example:

headers["accept"] = Resto::Format::Xml.accept

Returns:

  • (String)

    “application/xml, /



23
# File 'lib/resto/format/xml.rb', line 23

def accept; 'application/xml, */*'; end

.content_typeString

The content-type header when sending XML data.

Example:

headers["content-type"] = Resto::Format::Xml.content_type

Returns:

  • (String)

    “application/xml;charset=utf-8”



31
# File 'lib/resto/format/xml.rb', line 31

def content_type; 'application/xml;charset=utf-8'; end

.decode(xml, opts) ⇒ Array<Hash>

Converts an XML formatted String to an Array of Hashes.

Example:

xml = '<?xml version="1.0"?>
       <user>
         <name>Anders Törnqvist</name>
       </user>'
Xml.decode(xml, :xpath => 'user')
  # => [{ 'user': { 'name': 'Anders Törnqvist' } }]

Parameters:

  • xml (String)
  • opts (Hash)

    the options used when decoding the xml.

Options Hash (opts):

  • :xpath (String)

    the xpath to where the elements are found.

Returns:

  • (Array<Hash>)


49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/resto/format/xml.rb', line 49

def decode(xml, opts)
  xpath = AssertHash.keys(opts, :xpath).fetch(:xpath)

  doc =  Nokogiri::XML(xml)
  nodes =  doc.xpath(xpath)

  case nodes.size
  when 0
    [{}]
  when 1
    [elements_to_hash(nodes.first.children)]
  else
    nodes.map { |node| elements_to_hash(node.children) }
  end
end

.encode(hash, options = nil) ⇒ String

Converts a Hash to a XML formatted String.

Example:

Xml.encode({ root: { body: 'I am a body' } })
  # => "<?xml version=\"1.0\"?><root><body>I am a body</body></root>"

Parameters:

  • hash (Hash)
  • options (defaults to: nil)

    is not used.

Returns:

  • (String)


75
76
77
# File 'lib/resto/format/xml.rb', line 75

def encode(hash, options = nil)
  Nokogiri::XML::Builder.new { |xml| to_xml(hash, xml) }.to_xml
end

.extensionString

The extension name used (if required) as the URL suffix.

Example:

http://myhost.com:8085/bamboo/rest/api/latest/plan.xml

Returns:

  • (String)

    “xml”



85
# File 'lib/resto/format/xml.rb', line 85

def extension; 'xml'; end