[英]Rails 4: how to use string interpolation into Ruby regex in model helper
在我的Rails 4應用程序中,我具有以下帖子助手:
def link_highlight(string)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight">\1</span>')
if result1.nil?
init1
else
result1
end
end
我用它來鏈接樣式在post.copy
string
,感謝highlight
類。
現在,我想向該方法傳遞第二個argument
,這樣,由於不同的highlight
類,我可以對鏈接應用不同的樣式:
def link_highlight(string, color)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight-color">\1</span>')
if result1.nil?
init1
else
result1
end
end
當我這樣做時,應用於字符串中的鏈接的類實際上是highlight-color
。
相反,我想link_highlight(string, blue)
將highlight-blue
類應用於字符串。
——————
更新 :我嘗試了@dankohn提供的解決方案,但實際上不起作用。
如果我做:
def link_highlight(string, color)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight-#{color}">\1</span>')
if result1.nil?
init1
else
result1
end
end
然后我得到:
undefined local variable or method `color' for #<#<Class:0x007f911de61698>:0x007f911995f518>
因此,我也嘗試運行:
在我看來,但隨后回到最初的問題並得到:
#{"color"}">
顯示而不是顏色值。
——————
我怎樣才能更換color
由它的value
? 我可以使用字符串插值嗎?
試試: "<span class=\\"highlight-#{color}\\">\\1</span>"
嘗試使用塊,更容易處理:
string.gsub(/https?:\/\/\S+/){|link| "<span class=\"highlight-#{color}\">#{link}</span>"}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.