Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created June 23, 2011 12:13
Show Gist options
  • Save ashmoran/1042437 to your computer and use it in GitHub Desktop.
Save ashmoran/1042437 to your computer and use it in GitHub Desktop.
escape_xpath_string
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