Support for the XPath translate() function.
This commit is contained in:
parent
7f3f626744
commit
8295fa5783
|
@ -1002,6 +1002,35 @@ module Oga
|
||||||
return str.strip.gsub(/\s+/, ' ')
|
return str.strip.gsub(/\s+/, ' ')
|
||||||
end
|
end
|
||||||
|
|
||||||
|
##
|
||||||
|
# Processes the `translate()` function call.
|
||||||
|
#
|
||||||
|
# This function takes the string of the 1st argument and replaces all
|
||||||
|
# characters of the 2nd argument with those specified in the 3rd argument.
|
||||||
|
#
|
||||||
|
# @example
|
||||||
|
# translate("bar", "abc", "ABC") # => "BAr"
|
||||||
|
#
|
||||||
|
# @param [Oga::XML::NodeSet] context
|
||||||
|
# @param [Oga::XPath::Node] input
|
||||||
|
# @param [Oga::XPath::Node] find
|
||||||
|
# @param [Oga::XPath::Node] replace
|
||||||
|
# @return [String]
|
||||||
|
#
|
||||||
|
def on_call_translate(context, input, find, replace)
|
||||||
|
input_str = on_call_string(context, input)
|
||||||
|
find_chars = on_call_string(context, find).chars
|
||||||
|
replace_chars = on_call_string(context, replace).chars
|
||||||
|
replaced = input_str
|
||||||
|
|
||||||
|
find_chars.each_with_index do |char, index|
|
||||||
|
replace_with = replace_chars[index] ? replace_chars[index] : ''
|
||||||
|
replaced = replaced.gsub(char, replace_with)
|
||||||
|
end
|
||||||
|
|
||||||
|
return replaced
|
||||||
|
end
|
||||||
|
|
||||||
##
|
##
|
||||||
# Processes an `(int)` node.
|
# Processes an `(int)` node.
|
||||||
#
|
#
|
||||||
|
|
|
@ -0,0 +1,34 @@
|
||||||
|
require 'spec_helper'
|
||||||
|
|
||||||
|
describe Oga::XPath::Evaluator do
|
||||||
|
context 'translate() function' do
|
||||||
|
before do
|
||||||
|
@document = parse('<root><a>bar</a><b>abc</b><c>ABC</c></root>')
|
||||||
|
@evaluator = described_class.new(@document)
|
||||||
|
end
|
||||||
|
|
||||||
|
example 'translate a string using all string literals' do
|
||||||
|
@evaluator.evaluate('translate("bar", "abc", "ABC")').should == 'BAr'
|
||||||
|
end
|
||||||
|
|
||||||
|
example "remove characters that don't occur in the replacement string" do
|
||||||
|
@evaluator.evaluate('translate("-aaa-", "abc-", "ABC")').should == 'AAA'
|
||||||
|
end
|
||||||
|
|
||||||
|
example 'use the first character occurence in the search string' do
|
||||||
|
@evaluator.evaluate('translate("ab", "aba", "123")').should == '12'
|
||||||
|
end
|
||||||
|
|
||||||
|
example 'ignore excess characters in the replacement string' do
|
||||||
|
@evaluator.evaluate('translate("abc", "abc", "123456")').should == '123'
|
||||||
|
end
|
||||||
|
|
||||||
|
example 'translate a node set string using string literals' do
|
||||||
|
@evaluator.evaluate('translate(root/a, "abc", "ABC")').should == 'BAr'
|
||||||
|
end
|
||||||
|
|
||||||
|
example 'translate a node set string using other node set strings' do
|
||||||
|
@evaluator.evaluate('translate(root/a, root/b, root/c)').should == 'BAr'
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
Loading…
Reference in New Issue