Created
June 23, 2011 12:13
-
-
Save ashmoran/1042437 to your computer and use it in GitHub Desktop.
escape_xpath_string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def escape_xpath_string(string) | |
return "'#{string}'" if !string.include?("'") | |
components = string.split("'", -1).map { |component| "'#{component}'" } | |
"concat(#{components.join(%Q{,"'",})})" | |
end | |
title = "Let's Eat!" | |
# This is bad! | |
".//table//tr[td[. = '#{title}']]" == ".//table//tr[td[. = 'Let's Eat!']]" | |
# This is good! | |
".//table//tr[td[. = #{escape_xpath_string(title)}]]" == %Q{.//table//tr[td[. = concat('Let',"'",'s Eat!')]]} | |
# Examples that cover all cases: | |
escape_xpath_string("'Allo 'Allo is the dogs'") | |
#=> concat('',"'",'Allo ',"'",'Allo is the dogs',"'",'') | |
escape_xpath_string("'evenin") | |
#=> concat('',"'",'evenin') | |
escape_xpath_string("hello good lookin'") | |
#=> concat('hello good lookin',"'",'') | |
escape_xpath_string("this is boring") | |
#=> 'this is boring' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment