Ruby 字符串插值以将图像添加到 link 为图像 src 添加斜线前缀

Ruby string interpolation to add image to a link prefixes a slash to image src

我正在使用 Ruby 2.3.1p112,我正在尝试使用字符串插值来生成图像 link。但是,它错误地转义了 link src 引号,如下所示:src=\"http://localhost:3000/t\"。示例如下:

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

这不是查看代码;它发生在后端,这里是 class 提取并简化以显示问题

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  

您可以通过 运行在 irb 中使用下面的代码来重现它:

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

如果您 运行 上面的代码,您会看到 puts 语句 记录了正确的内容并且图像 src 是:

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

但是如果没有 puts 语句,图像 src 会被转义引号包围: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>

删除图像 src 中的引号转义的最佳方法是什么?

没有反斜杠。您的代码工作正常。

You can reproduce it by running the code below in irb

irb 中尝试 运行 这个:

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

你所看到的只是当直接输出变量时,irb显示的是原始字符串。而且,由于字符串以 " 个字符结尾,因此有必要在显示时转义输出中的任何 " 个字符。

如果字符串确实 确实 包含文字反斜杠,您会看到什么而不是

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

将是:

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