簡體   English   中英

Ruby字符串插值以將圖像添加到鏈接,在圖像src之前加一個斜杠

[英]Ruby string interpolation to add image to a link prefixes a slash to image src

我正在使用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中的引號轉義的最佳方法是什么?

沒有反斜杠。 您的代碼工作正常。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM