From 98527d0d14e51957d9b5593e6598ce2b892439c3 Mon Sep 17 00:00:00 2001 From: John Barker Date: Sun, 5 Feb 2012 14:30:02 -0500 Subject: [PATCH] Add support for xpath starts-with function --- lib/xpath/dsl.rb | 4 ++++ lib/xpath/renderer.rb | 5 ++++- spec/xpath_spec.rb | 19 +++++++++++++++++++ 3 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/xpath/dsl.rb b/lib/xpath/dsl.rb index 694920b..69a7f8d 100644 --- a/lib/xpath/dsl.rb +++ b/lib/xpath/dsl.rb @@ -33,6 +33,10 @@ def contains(expression) Expression.new(:contains, current, expression) end + def starts_with(expression) + Expression.new(:starts_with, current, expression) + end + def text Expression.new(:text, current) end diff --git a/lib/xpath/renderer.rb b/lib/xpath/renderer.rb index 71186dd..6f4367b 100644 --- a/lib/xpath/renderer.rb +++ b/lib/xpath/renderer.rb @@ -123,9 +123,12 @@ def contains(current, value) "contains(#{current}, #{value})" end + def starts_with(current, value) + "starts-with(#{current}, #{value})" + end + def and(one, two) "(#{one} and #{two})" - end def or(one, two) diff --git a/spec/xpath_spec.rb b/spec/xpath_spec.rb index a271c27..3c0d453 100644 --- a/spec/xpath_spec.rb +++ b/spec/xpath_spec.rb @@ -125,6 +125,25 @@ def xpath(predicate=nil, &block) end end + describe '#starts_with' do + it "should find nodes that begin with the given string" do + @results = xpath do |x| + x.descendant(:*).where(x.attr(:id).starts_with('foo')) + end + @results.size.should == 2 + @results[0][:id].should == "foo" + @results[1][:id].should == "fooDiv" + end + + it "should find nodes that contain the given expression" do + @results = xpath do |x| + expression = x.anywhere(:div).where(x.attr(:title) == 'fooDiv').attr(:id) + x.descendant(:div).where(x.attr(:title).starts_with(expression)) + end + @results[0][:id].should == "foo" + end + end + describe '#text' do it "should select a node's text" do @results = xpath { |x| x.descendant(:p).where(x.text == 'Bax') }