Class: LibraryThing::NodeWrapper
- Inherits:
-
Object
- Object
- LibraryThing::NodeWrapper
- Defined in:
- lib/librarything/resource.rb
Overview
Helper class to wrap a Nokogiri node. It includes a simplified method for accessing DOM content.
Instance Attribute Summary collapse
-
#node ⇒ Object
readonly
Returns the value of attribute node.
Instance Method Summary collapse
-
#[](name) ⇒ Object
Extracts values from the node.
-
#content ⇒ Object
Returns the content of the node.
-
#initialize(node) ⇒ NodeWrapper
constructor
Creates a new wrapped XML node.
Constructor Details
#initialize(node) ⇒ NodeWrapper
Creates a new wrapped XML node
9 10 11 |
# File 'lib/librarything/resource.rb', line 9 def initialize(node) @node = node end |
Instance Attribute Details
#node ⇒ Object (readonly)
Returns the value of attribute node.
6 7 8 |
# File 'lib/librarything/resource.rb', line 6 def node @node end |
Instance Method Details
#[](name) ⇒ Object
Extracts values from the node.
-
If the name matches the name of an attribute, the value of that attribute will be returned
-
If the name matches the name of a single child element, that element is returned.
-
If the matching child element only contains text data, the text data is returned.
-
If the matching child element is named xxxList, an array of the children of the element is returned
-
If there is more that one matching child element, they are returned as an array.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/librarything/resource.rb', line 26 def [](name) # Check for attributes first. Why? It works for the LT xml (for now). if @node.attributes.has_key?(name) return @node.attributes[name].value end # Find child elements with that name children = @node.xpath("./lt:#{name}") if children.size == 1 child = children.first if self.text_element?(child) return child.children.first.content elsif child.name =~ /^[\w]*List$/ # LT-specific hack to simplify access to lists. Ill-advised? return wrap_children(child.children) else return NodeWrapper.new(child) end elsif children.size > 1 return wrap_children(children) else return nil end end |
#content ⇒ Object
Returns the content of the node
14 15 16 |
# File 'lib/librarything/resource.rb', line 14 def content @node.content end |