0

I am using Ruby 2.3.1p112 and I am trying to use string interpolation to produce an image link. However, it incorrectly escapes the link src quotes, like this: src=\"http://localhost:3000/t\". The example is shown below:

 <a href=www.google.com target='_blank'> google.com \"<img src=\"http://localhost:3000/t\" width='1' height='1'>\"</a>

This is not view code; it happens on the backend and here is the class extracted out and simplified to show the problem

class Link
  require 'uri'

  def self.link_name(url)
    uri = URI.parse(url)
    uri = URI.parse("http://#{url}") if uri.scheme.nil?
    host = uri.host.downcase
    host.start_with?('www.') ? host[4..-1] : host
  end

  def self.url_regex
    /(http:|www.)[a-zA-Z0-9\/:\.\?]*/
  end

  def self.link_image(e)
    email = ['b@y.com', 'x@go.com']
      email.map do |p|
        token = new.generate_email_click_tracking_img
        e.gsub(url_regex) do |url|

        puts "token inloop is <a href=#{url}>#{link_name(url)}  #{token} </a>"

        "<a href=#{url} target='_blank'> #{link_name(url)} \"#{token}\"</a>"
      end   
    end
  end

  def generate_email_click_tracking_img
    url = "http://localhost:3000/t"
    "<img src=\"#{url}\" width='1' height='1'>"
  end

end  

You can reproduce it by running the code below in irb:

a =  "me in www.google.com, you in http://www.facebook.com"
Link.link_image(a)

If you run the code above, you will see that the puts statement logs the correct thing and the image src is :

<a href=http://www.facebook.com>facebook.com  <img src="http://localhost:3000/t" width='1' height='1'> </a>

But without the puts statement the image src is surrounded with escaped quotes: http://localhost:3000/t\"

<a href=http://www.facebook.com target='_blank'> facebook.com \"<img src=\"http://localhost:3000/t\" width='1' height='1'>\"</a>

What is the best way to to remove the quote escapes in the image src?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
brg
  • 3,915
  • 8
  • 37
  • 66

1 Answers1

2

There is no backslash. Your code is working just fine.

You can reproduce it by running the code below in irb

Try running this in irb:

puts '"hello"'
# => "hello"
'"hello"'
# => "\"hello\""

All you are seeing is that when directly outputting a variable, irb is displaying the raw string. And, because the string is terminated by " characters, it is therefore necessary to escape any " characters inside the output, upon display.

If the string really did contain literal backslashes, what you would see instead of

<a href=http://www.facebook.com target='_blank'> facebook.com \"<img src=\"http://localhost:3000/t\" width='1' height='1'>\"</a>

Would be:

<a href=http://www.facebook.com target='_blank'> facebook.com \\\"<img src=\\\"http://localhost:3000/t\\\" width='1' height='1'>\\\"</a>
Tom Lord
  • 27,404
  • 4
  • 50
  • 77