Rails 4:如何在模型助手中使用字符串插值到 Ruby 正则表达式中
Rails 4: how to use string interpolation into Ruby regex in model helper
在我的 Rails 4 应用程序中,我有以下 post 助手:
def link_highlight(string)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight"></span>')
if result1.nil?
init1
else
result1
end
end
我用它来设置 post.copy
string
中的链接样式,这要感谢 highlight
class。
现在,我想将第二个 argument
传递给该方法,这样我就可以对链接应用不同的样式,这要归功于不同的 highlight
classes:
def link_highlight(string, color)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight-color"></span>')
if result1.nil?
init1
else
result1
end
end
当我这样做时,应用于字符串中链接的 class 实际上是 highlight-color
.
相反,我想 link_highlight(string, blue)
将 highlight-blue
class 应用于字符串。
——————
更新:我尝试了@dankohn 提供的解决方案,但它实际上不起作用。
如果我这样做:
def link_highlight(string, color)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight-#{color}"></span>')
if result1.nil?
init1
else
result1
end
end
然后我得到:
undefined local variable or method `color' for #<#<Class:0x007f911de61698>:0x007f911995f518>
所以,我也试过运行:
在我看来,但后来我回到最初的问题并得到:
#{"color"}">
显示而不是颜色值。
——————
如何用 value
替换 color
?我可以使用字符串插值吗?
尝试:"<span class=\"highlight-#{color}\"></span>"
用积木试试,比较好对付:
string.gsub(/https?:\/\/\S+/){|link| "<span class=\"highlight-#{color}\">#{link}</span>"}
在我的 Rails 4 应用程序中,我有以下 post 助手:
def link_highlight(string)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight"></span>')
if result1.nil?
init1
else
result1
end
end
我用它来设置 post.copy
string
中的链接样式,这要感谢 highlight
class。
现在,我想将第二个 argument
传递给该方法,这样我就可以对链接应用不同的样式,这要归功于不同的 highlight
classes:
def link_highlight(string, color)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight-color"></span>')
if result1.nil?
init1
else
result1
end
end
当我这样做时,应用于字符串中链接的 class 实际上是 highlight-color
.
相反,我想 link_highlight(string, blue)
将 highlight-blue
class 应用于字符串。
——————
更新:我尝试了@dankohn 提供的解决方案,但它实际上不起作用。
如果我这样做:
def link_highlight(string, color)
init1 = string
result1 = string.to_s.gsub!(/((https|http)?:\/\/[\S]+)/, '<span class="highlight-#{color}"></span>')
if result1.nil?
init1
else
result1
end
end
然后我得到:
undefined local variable or method `color' for #<#<Class:0x007f911de61698>:0x007f911995f518>
所以,我也试过运行:
在我看来,但后来我回到最初的问题并得到:
#{"color"}">
显示而不是颜色值。
——————
如何用 value
替换 color
?我可以使用字符串插值吗?
尝试:"<span class=\"highlight-#{color}\"></span>"
用积木试试,比较好对付:
string.gsub(/https?:\/\/\S+/){|link| "<span class=\"highlight-#{color}\">#{link}</span>"}