-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
attributes.cr
75 lines (57 loc) · 1.31 KB
/
attributes.cr
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
require "./node"
class XML::Attributes
include Enumerable(Node)
def initialize(@node : Node)
end
def empty? : Bool
return true unless @node.element?
props = self.props
props.null?
end
def [](index : Int) : XML::Node
# TODO: Optimize to avoid double iteration
size = self.size
index += size if index < 0
unless 0 <= index < size
raise IndexError.new
end
each_with_index do |node, i|
return node if i == index
end
raise IndexError.new
end
def [](name : String) : XML::Node
self[name]? || raise KeyError.new("Missing attribute: #{name}")
end
def []?(name : String) : XML::Node?
find { |node| node.name == name }
end
def []=(name : String, value)
LibXML.xmlSetProp(@node, name, value.to_s)
value
end
def delete(name : String) : String?
value = self[name]?.try &.content
res = LibXML.xmlUnsetProp(@node, name)
value if res == 0
end
def each(&) : Nil
return unless @node.element?
props = self.props
until props.null?
yield Node.new(props)
props = props.value.next
end
end
def to_s(io : IO) : Nil
io << '['
join io, ", ", &.inspect(io)
io << ']'
end
def inspect(io : IO) : Nil
to_s(io)
end
protected def props
@node.to_unsafe.value.properties
end
end