cheeseandpepper cheeseandpepper - 7 months ago 16
Ruby Question

How can I escape " or ' when it is a variable in ruby or rails?

I'm building a js file on the backend for future use and need to convert macros into js code. My

gsub
in the method below was working fine until I had a url with double quotes. If I have a variable
quote_type = "'"
, how can I interpolate that as an escaped quote? In other words..

"'"
becomes
"\'"
and
'"'
becomes
'\"'


Here's my existing method and I just added the
quote_type
variable to try this out.

def substitute_timestamp_macro!(string)
quote_type = string[0]
string.gsub('[timestamp]', '\' + new Date().getTime() + \'')
end


edit: example string would be
"https://doesntmatter.com/stuff/123;time=[timestamp]?"


edit 2: Here is the expected result:
"https://doesntmatter.com/stuff/123;time=" + new Date().getTime() + "?"


here is the actual result
"https://doesntmatter.com/stuff/123;time=' + new Date().getTime() + '?"


notice in my
gsub
i hard coded an escaped single quote. I now want to use the variable to match the input quote so if it's single, use single, and if double, use double

Answer

Consider %() to wrap your string:

def substitute_timestamp_macro!(string)
  %("#{string}").gsub("[timestamp]", %(" + new Date().getTime() + "))
end

Note that this will render a string with escaped double quotes:

substitute_timestamp_macro!("https://doesntmatter.com/stuff/123;time=[timestamp]")
=> "\"https://doesntmatter.com/stuff/123;time=\" + new Date().getTime() + \"?\""

Which will be interpreted properly when you render this to a buffer:

puts substitute_timestamp_macro!("https://doesntmatter.com/stuff/123;time=[timestamp]")
=> "https://doesntmatter.com/stuff/123;time=" + new Date().getTime() + "?"