faraday_curl icon indicating copy to clipboard operation
faraday_curl copied to clipboard

Escape single quote correctly.

Open ne-sachirou opened this issue 5 years ago • 0 comments

\\' has a special meaning in String#gsub's replacement string.

https://docs.ruby-lang.org/en/2.6.0/String.html#method-i-gsub

If replacement is a String it will be substituted for the matched text. It may contain back-references to the pattern's capture groups of the form \d, where d is a group number, or \k, where n is a group name. If it is a double-quoted string, both back-references must be preceded by an additional backslash. However, within replacement the special match variables, such as $&, will not refer to the current match.

So \\' is $'.

https://docs.ruby-lang.org/en/2.6.0/globals_rdoc.html

$' The string to the right of the last successful match.

It works like this.

irb> "exampl'e".gsub("'", "\\'")
=> "examplee"
irb> "examp'le".gsub("'", "\\'")
=> "examplele"

It's implemented in https://github.com/ruby/ruby/blob/3df37259d81d9fc71f8b4f0b8d45dc9d0af81ab4/re.c#L3887 since before 1998.

So current Faraday::Curl#quote dosen't work correctly.

In this patch I use a block argument.

irb> "exampl'e".gsub("'") { "\\'" }
=> "exampl\\'e"

ne-sachirou avatar Oct 04 '19 09:10 ne-sachirou