Skip to content

Escape single quote correctly.#2

Open
ne-sachirou wants to merge 4 commits intomauricio:masterfrom
ne-sachirou:feature/escape_correctly
Open

Escape single quote correctly.#2
ne-sachirou wants to merge 4 commits intomauricio:masterfrom
ne-sachirou:feature/escape_correctly

Conversation

@ne-sachirou
Copy link

\\' 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 ne-sachirou force-pushed the feature/escape_correctly branch from de9b74f to 7abc305 Compare October 7, 2019 03:01

def quote(value)
value.gsub("'", "\\'")
value.gsub("'") { "'\\''" }

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

value is not always a String. In some case it can be a Boolean

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants