Class: Goliath::Rack::Formatters::XML
- Inherits:
-
Object
- Object
- Goliath::Rack::Formatters::XML
show all
- Includes:
- AsyncMiddleware
- Defined in:
- lib/goliath/rack/formatters/xml.rb
Overview
A XML formatter. Attempts to convert your data into an XML document.
Instance Method Summary
collapse
#call, #final_response?, #hook_into_callback_chain
Methods included from Validator
safely, validation_error
Constructor Details
#initialize(app, opts = {}) ⇒ XML
Returns a new instance of XML.
14
15
16
17
18
19
|
# File 'lib/goliath/rack/formatters/xml.rb', line 14
def initialize(app, opts = {})
@app = app
@opts = opts
@opts[:root] ||= 'results'
@opts[:item] ||= 'item'
end
|
Instance Method Details
#array_to_xml(content, item = 'item') ⇒ Object
62
63
64
65
66
|
# File 'lib/goliath/rack/formatters/xml.rb', line 62
def array_to_xml(content, item='item')
xml_string = ''
content.each { |value| xml_string << xml_item(item, value) }
xml_string
end
|
#hash_to_xml(content) ⇒ Object
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/goliath/rack/formatters/xml.rb', line 51
def hash_to_xml(content)
xml_string = ''
if content.key?('meta')
xml_string += xml_item('meta', content['meta'])
content.delete('meta')
end
content.each_pair { |key, value| xml_string << xml_item(key, value) }
xml_string
end
|
#post_process(env, status, headers, body) ⇒ Object
21
22
23
24
25
26
|
# File 'lib/goliath/rack/formatters/xml.rb', line 21
def post_process(env, status, , body)
if xml_response?()
body = [to_xml(body)]
end
[status, , body]
end
|
#string_to_xml(content) ⇒ Object
47
48
49
|
# File 'lib/goliath/rack/formatters/xml.rb', line 47
def string_to_xml(content)
::Rack::Utils.escape_html(content.to_s)
end
|
#to_xml(content, fragment = false) ⇒ Object
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# File 'lib/goliath/rack/formatters/xml.rb', line 32
def to_xml(content, fragment=false)
xml_string = ''
xml_string << (@opts[:root]) unless fragment
xml_string << case(content.class.to_s)
when "Hash" then hash_to_xml(content)
when "Array" then array_to_xml(content, @opts[:item])
when "String" then string_to_xml(content)
else string_to_xml(content)
end
xml_string << (@opts[:root]) unless fragment
xml_string
end
|
72
73
74
|
# File 'lib/goliath/rack/formatters/xml.rb', line 72
def (root)
"</#{root}>"
end
|
68
69
70
|
# File 'lib/goliath/rack/formatters/xml.rb', line 68
def (root)
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<#{root}>"
end
|
#xml_item(key, value) ⇒ Object
76
77
78
|
# File 'lib/goliath/rack/formatters/xml.rb', line 76
def xml_item(key, value)
"<#{key}>#{to_xml(value, true)}</#{key}>\n"
end
|
#xml_response?(headers) ⇒ Boolean
28
29
30
|
# File 'lib/goliath/rack/formatters/xml.rb', line 28
def xml_response?()
['Content-Type'] =~ %r{^application/xml}
end
|