Class: Resto::Format::Xml
- Inherits:
-
Object
- Object
- Resto::Format::Xml
- Extended by:
- Resto::Format
- Defined in:
- lib/resto/format/xml.rb
Overview
Used when sending and receiveing XML data.
Class Method Summary collapse
-
.accept ⇒ String
The accept header when sending XML data.
-
.content_type ⇒ String
The content-type header when sending XML data.
-
.decode(xml, opts) ⇒ Array<Hash>
Converts an XML formatted String to an Array of Hashes.
-
.encode(hash, options = nil) ⇒ String
Converts a Hash to a XML formatted String.
-
.extension ⇒ String
The extension name used (if required) as the URL suffix.
Methods included from Resto::Format
accept, content_type, decode, encode, extension, get
Class Method Details
.accept ⇒ String
23 |
# File 'lib/resto/format/xml.rb', line 23 def accept; 'application/xml, */*'; end |
.content_type ⇒ String
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' } }]
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>"
75 76 77 |
# File 'lib/resto/format/xml.rb', line 75 def encode(hash, = nil) Nokogiri::XML::Builder.new { |xml| to_xml(hash, xml) }.to_xml end |
.extension ⇒ String
The extension name used (if required) as the URL suffix.
Example:
http://myhost.com:8085/bamboo/rest/api/latest/plan.xml
85 |
# File 'lib/resto/format/xml.rb', line 85 def extension; 'xml'; end |