roxo 0.0.2 → 0.0.3
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/roxo.rb +10 -25
- data/roxo.gemspec +1 -1
- metadata +2 -2
data/lib/roxo.rb
CHANGED
@@ -1,11 +1,6 @@
|
|
1
|
-
require 'rubygems'
|
2
1
|
require 'active_support/inflector'
|
3
2
|
require 'libxml'
|
4
3
|
|
5
|
-
# z = ROXO.new("<foo a='zxcv'><bar><baz>asdf</baz></bar></foo>")
|
6
|
-
# z.a #=> "zxcv"
|
7
|
-
# z.bar.baz #=> "asdf"
|
8
|
-
|
9
4
|
# Ruby Objects as XML Objects
|
10
5
|
class ROXO
|
11
6
|
instance_methods.each do |meth|
|
@@ -14,9 +9,8 @@ class ROXO
|
|
14
9
|
|
15
10
|
include Comparable
|
16
11
|
|
17
|
-
# Accessors and other one-liners
|
18
12
|
attr_reader :raw, :name, :value, :children
|
19
|
-
def __attributes; @attributes;
|
13
|
+
def __attributes; @attributes.sort; end
|
20
14
|
def attributes; @attributes.keys; end
|
21
15
|
def terminal?; @children.size.zero?; end # A node is terminal if we can't descend any further
|
22
16
|
def has?(o); !! send(o); end # Boolean. Does this exist?
|
@@ -24,34 +18,26 @@ class ROXO
|
|
24
18
|
def to_s; @value; end
|
25
19
|
|
26
20
|
def initialize(xml)
|
27
|
-
|
28
|
-
|
29
|
-
xml = ::LibXML::XML::Parser.string(xml.send(method))
|
30
|
-
end
|
31
|
-
|
21
|
+
xml = ::LibXML::XML::Parser.string(xml).parse.root unless xml.kind_of?(LibXML::XML::Node)
|
22
|
+
|
32
23
|
@raw, @name, @attributes = xml, xml.name, xml.attributes.to_h
|
33
|
-
|
34
24
|
@children = xml.children.select(&:element?).group_by{|c|c.name.to_sym}
|
35
|
-
|
25
|
+
|
36
26
|
text_value = xml.children.select(&:text?).map(&:to_s).reject(&:empty?).join
|
37
27
|
cdata_value = xml.children.select(&:cdata?).map{|c|c.to_s.chomp(']]>').sub('<![CDATA[', '')}.join
|
38
28
|
@value = text_value.empty? ? cdata_value : text_value
|
39
29
|
end
|
40
30
|
|
41
31
|
def inspect
|
42
|
-
terminal? ? value.inspect : "#<ROXO
|
32
|
+
terminal? ? value.inspect : "#<ROXO:0x#{object_id.to_s(16)} @name=\"#{@name}\", ...>"
|
43
33
|
end
|
44
34
|
|
45
35
|
def <=>(other)
|
46
|
-
|
47
|
-
|
48
|
-
|
49
|
-
|
50
|
-
|
51
|
-
our_nodes = self.children.values.flatten.map{|n|self.class.new(n)}
|
52
|
-
their_nodes = other.children.values.flatten.map{|n|self.class.new(n)}
|
53
|
-
|
54
|
-
our_nodes.sort <=> their_nodes.sort
|
36
|
+
[:class, :__attributes, :value, :name].each do |key|
|
37
|
+
return z unless (z = self.send(key) <=> other.send(key)).zero?
|
38
|
+
end
|
39
|
+
nodes = lambda{|obj|obj.children.values.flatten.map{|n|self.class.new(n)}}
|
40
|
+
nodes[self] <=> nodes[other]
|
55
41
|
end
|
56
42
|
|
57
43
|
def method_missing(sym, *args)
|
@@ -65,4 +51,3 @@ class ROXO
|
|
65
51
|
end
|
66
52
|
|
67
53
|
end
|
68
|
-
|
data/roxo.gemspec
CHANGED