diff --git a/lib/oga/xpath/evaluator.rb b/lib/oga/xpath/evaluator.rb index 03c6ba2..1ca2d28 100644 --- a/lib/oga/xpath/evaluator.rb +++ b/lib/oga/xpath/evaluator.rb @@ -982,6 +982,26 @@ module Oga return on_call_string(context, expression).length.to_f end + ## + # Processes the `normalize-space()` function call. + # + # This function strips the 1st argument string *or* the current context + # node of leading/trailing whitespace as well as replacing multiple + # whitespace sequences with single spaces. + # + # @example + # normalize-space(" fo o ") # => "fo o" + # + # @param [Oga::XML::NodeSet] context + # @param [Oga::XPath::Node] expression + # @return [String] + # + def on_call_normalize_space(context, expression = nil) + str = on_call_string(context, expression) + + return str.strip.gsub(/\s+/, ' ') + end + ## # Processes an `(int)` node. # diff --git a/spec/oga/xpath/evaluator/calls/normalize_space_spec.rb b/spec/oga/xpath/evaluator/calls/normalize_space_spec.rb new file mode 100644 index 0000000..9337a8a --- /dev/null +++ b/spec/oga/xpath/evaluator/calls/normalize_space_spec.rb @@ -0,0 +1,40 @@ +require 'spec_helper' + +describe Oga::XPath::Evaluator do + context 'normalize-space() function' do + before do + @document = parse(' fo o ') + @evaluator = described_class.new(@document) + end + + context 'outside predicates' do + example 'normalize a literal string' do + @evaluator.evaluate('normalize-space(" fo o ")').should == 'fo o' + end + + example 'normalize a string in a node set' do + @evaluator.evaluate('normalize-space(root/a)').should == 'fo o' + end + + example 'normalize an integer' do + @evaluator.evaluate('normalize-space(10)').should == '10' + end + + example 'normalize a float' do + @evaluator.evaluate('normalize-space(10.5)').should == '10.5' + end + end + + context 'inside predicates' do + before do + @set = @evaluator.evaluate('root/a[normalize-space()]') + end + + it_behaves_like :node_set, :length => 1 + + example 'return the node' do + @set[0].should == @document.children[0].children[0] + end + end + end +end