Support for the XPath normalize-space() function.

This commit is contained in:
Yorick Peterse 2014-08-26 00:06:58 +02:00
parent 06bed1cfdd
commit 7f3f626744
2 changed files with 60 additions and 0 deletions

View File

@ -982,6 +982,26 @@ module Oga
return on_call_string(context, expression).length.to_f return on_call_string(context, expression).length.to_f
end 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. # Processes an `(int)` node.
# #

View File

@ -0,0 +1,40 @@
require 'spec_helper'
describe Oga::XPath::Evaluator do
context 'normalize-space() function' do
before do
@document = parse('<root><a> fo o </a></root>')
@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 <a> node' do
@set[0].should == @document.children[0].children[0]
end
end
end
end