From 585b3535b2b07109d09b97e39214ea6413fd932e Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Wed, 27 Aug 2014 20:26:27 +0200 Subject: [PATCH] Support for the XPath lang() function. --- lib/oga/xpath/evaluator.rb | 29 +++++++++++++ spec/oga/xpath/evaluator/calls/lang_spec.rb | 46 +++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 spec/oga/xpath/evaluator/calls/lang_spec.rb diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index fa7e680..d906ae5 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -1103,6 +1103,35 @@ module Oga return false end + ## + # Processes the `lang()` function call. + # + # This function returns `true` if the current context node is in the given + # language, `false` otherwise. + # + # The language is based on the value of the "xml:lang" attribute of either + # the context node or an ancestor node (in case the context node has no + # such attribute). + # + # @param [Oga::XML::NodeSet] context + # @param [Oga::XPath::Node] language + # @return [TrueClass|FalseClass] + # + def on_call_lang(context, language) + lang_str = on_call_string(context, language) + node = current_node + + while node.respond_to?(:attribute) + found = node.attribute('xml:lang') + + return found.value == lang_str if found + + node = node.parent + end + + return false + end + ## # Processes an `(int)` node. # diff --git a/spec/oga/xpath/evaluator/calls/lang_spec.rb b/spec/oga/xpath/evaluator/calls/lang_spec.rb new file mode 100644 index 0000000..4298056 --- /dev/null +++ b/spec/oga/xpath/evaluator/calls/lang_spec.rb @@ -0,0 +1,46 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'lang() function' do + before do + @document = parse('') + @evaluator = described_class.new(@document) + end + + context 'selecting nodes with lang="en"' do + before do + @set = @evaluator.evaluate('root[lang("en")]') + end + + it_behaves_like :node_set, :length => 1 + + example 'return the node' do + @set[0].should == @document.children[0] + end + end + + context 'selecting nodes with lang="nl"' do + before do + @set = @evaluator.evaluate('root/a[lang("nl")]') + end + + it_behaves_like :node_set, :length => 1 + + example 'return the second node' do + @set[0].should == @document.children[0].children[1] + end + end + + context 'inheriting the language from ancestor nodes' do + before do + @set = @evaluator.evaluate('root/a[lang("en")]') + end + + it_behaves_like :node_set, :length => 1 + + example 'return the first node' do + @set[0].should == @document.children[0].children[0] + end + end + end +end