forked from websdotcom/constant_contact
/
atom_format.rb
80 lines (68 loc) · 1.94 KB
/
atom_format.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
73
74
75
76
77
78
79
80
require 'rexml/document'
module ActiveResource
module Formats
module AtomFormat
extend self
def extension
"atom"
end
def mime_type
"application/atom+xml"
end
def encode(hash, options={})
hash.to_xml(options)
end
def decode(xml)
return [] if no_content?(xml)
result = Hash.from_xml(from_atom_data(xml))
is_collection?(xml) ? result['records'] : result.values.first
end
private
def from_atom_data(xml)
if is_collection?(xml)
result = content_from_collection(xml)
else
result = content_from_single_record(xml)
end
result.delete('xmlns')
return result
end
def no_content?(xml)
doc = REXML::Document.new(xml)
REXML::XPath.match(doc,'//content').size == 0
end
def is_collection?(xml)
doc = REXML::Document.new(xml)
REXML::XPath.match(doc,'//content').size > 1
end
def content_from_single_record(xml)
doc = REXML::Document.new(xml)
str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
REXML::XPath.each(doc, '//content') do |e|
content = e.children[1]
str << content.to_s
end
str
end
def content_from_collection(xml)
doc = REXML::Document.new(xml)
str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><records type=\"array\">"
REXML::XPath.each(doc, '//content') do |e|
content = e.children[1]
str << content.to_s
end
str << "</records>"
str
end
def content_from_member(xml)
doc = REXML::Document.new(xml)
str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
REXML::XPath.each(doc, '//content') do |e|
content = e.children[1].children
str << content.to_s
end
str
end
end
end
end