【问题标题】:Ruby string interpolation to add image to a link prefixes a slash to image src将图像添加到链接的 Ruby 字符串插值在图像 src 中添加斜杠前缀
【发布时间】:2016-09-22 04:15:45
【问题描述】:

我正在使用 Ruby 2.3.1p112,我正在尝试使用字符串插值来生成图像链接。但是,它错误地转义了链接 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 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 中的引号转义的最佳方法是什么?

【问题讨论】:

  • “斜杠前缀”是指“反斜杠后缀”?

标签: ruby-on-rails ruby string-interpolation ruby-2.2


【解决方案1】:

没有反斜杠。您的代码运行良好。

您可以通过在 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>

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2020-05-26
    • 2013-06-18
    • 2013-05-29
    • 2023-03-10
    • 1970-01-01
    • 2019-05-22
    • 2021-06-10
    • 1970-01-01
    相关资源
    最近更新 更多