diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index a555e01..681c64a 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -811,7 +811,7 @@ module Oga # Processes the `starts-with()` function call. # # This function call returns `true` if the string in the 1st argument - # starts with the string in the 2nd argument. + # starts with the string in the 2nd argument. Node sets can also be used. # # @example # starts-with("hello world", "hello") # => true @@ -828,6 +828,22 @@ module Oga return haystack_str.start_with?(needle_str) end + ## + # Processes the `contains()` function call. + # + # This function call returns `true` if the string in the 1st argument + # contains the string in the 2nd argument. Node sets can also be used. + # + # @example + # contains("hello world", "o w") # => true + # + def on_call_contains(context, haystack, needle) + haystack_str = on_call_string(context, haystack) + needle_str = on_call_string(context, needle) + + return haystack_str.include?(needle_str) + end + ## # Processes an `(int)` node. # diff --git a/spec/oga/xpath/evaluator/calls/contains_spec.rb b/spec/oga/xpath/evaluator/calls/contains_spec.rb new file mode 100644 index 0000000..3725ed4 --- /dev/null +++ b/spec/oga/xpath/evaluator/calls/contains_spec.rb @@ -0,0 +1,38 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'contains() function' do + before do + @document = parse('foofoobar') + @evaluator = described_class.new(@document) + end + + example 'return true if the 1st string contains the 2nd string' do + @evaluator.evaluate('contains("foobar", "oo")').should == true + end + + example "return false if the 1st string doesn't contain the 2nd string" do + @evaluator.evaluate('contains("foobar", "baz")').should == false + end + + example 'return true if the 1st node set contains the 2nd string' do + @evaluator.evaluate('contains(root/a, "oo")').should == true + end + + example 'return true if the 1st node set contains the 2nd node set' do + @evaluator.evaluate('contains(root/b, root/a)').should == true + end + + example "return false if the 1st node doesn't contain the 2nd node set" do + @evaluator.evaluate('contains(root/a, root/b)').should == false + end + + example 'return true if the 1st string contains the 2nd node set' do + @evaluator.evaluate('contains("foobar", root/a)').should == true + end + + example 'return true when using two empty strings' do + @evaluator.evaluate('contains("", "")').should == true + end + end +end