Skip to content

Commit

Permalink
Added some sugar to XmlQueryFront
Browse files Browse the repository at this point in the history
  • Loading branch information
troelskn committed Jun 23, 2009
1 parent 08ecc1e commit d00d1ae
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
34 changes: 32 additions & 2 deletions lib/handsoap/xml_query_front.rb
Expand Up @@ -62,6 +62,36 @@ def self.parse_string(xml_string, driver)
end
end

# NodeSelection is a wrapper around Array, that implicitly delegates BaseDriver methods to the first element.
#
# It makes mapping code prettier, since you often need to access the first element of a selection.
class NodeSelection < Array
def to_i
self.first.to_i if self.any?
end
def to_f
self.first.to_f if self.any?
end
def to_boolean
self.first.to_boolean if self.any?
end
def to_date
self.first.to_date if self.any?
end
def node_name
self.first.node_name if self.any?
end
def xpath(expression, ns = nil)
self.first.xpath(expression, ns)
end
def to_s
self.first.to_s if self.any?
end
def to_xml
self.first.to_xml if self.any?
end
end

# Wraps the underlying (native) xml driver, and provides a uniform interface.
module BaseDriver
def initialize(element, namespaces = {})
Expand Down Expand Up @@ -142,9 +172,9 @@ def to_s
def to_xml
raise NotImplementedError.new
end
# Alias for +xpath+
# Calls +xpath+ and wraps the result in a +NodeSelection+.
def /(expression)
self.xpath(expression)
NodeSelection.new self.xpath(expression)
end
end

Expand Down
5 changes: 5 additions & 0 deletions tests/xml_query_front_test.rb
Expand Up @@ -150,6 +150,11 @@ def test_serialize
)?</bar>
</foo>")
end
def test_query_by_syntactic_sugar
doc = create_default_document
assert_equal 3, (doc/"//aws:OperationRequest[1]/aws:RequestId").to_i
assert_equal (doc/"//aws:OperationRequest[1]/aws:RequestId").to_i, (doc/"//aws:OperationRequest[1]/aws:RequestId").first.to_i
end
end

class TestOfREXMLDriver < Test::Unit::TestCase
Expand Down

0 comments on commit d00d1ae

Please sign in to comment.