简体   繁体   English

Rails 4:如何在模型助手中使用字符串插值到Ruby regex中

[英]Rails 4: how to use string interpolation into Ruby regex in model helper

In my Rails 4 app, I have the following post 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

I use it to style links in the post.copy string , thanks to the highlight class. 我用它来链接样式在post.copy string ,感谢highlight类。

Now, I would like to pass a second argument to the method, so that I can apply different styles to the links, thanks to different highlight classes: 现在,我想向该方法传递第二个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

When I do that, the class applied to the links in the string is actually highlight-color . 当我这样做时,应用于字符串中的链接的类实际上是highlight-color

Instead, I would like to link_highlight(string, blue) to apply the highlight-blue class to the string. 相反,我想link_highlight(string, blue)highlight-blue类应用于字符串。

————— ——————

UPDATE : I tried the solution offered by @dankohn but it is actually not working. 更新 :我尝试了@dankohn提供的解决方案,但实际上不起作用。

If I do: 如果我做:

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 

Then I get: 然后我得到:

undefined local variable or method `color' for #<#<Class:0x007f911de61698>:0x007f911995f518>

So, I also tried to run: 因此,我也尝试运行:

in my view, but then I get back to the initial problem and get: 在我看来,但随后回到最初的问题并得到:

#{"color"}">

displayed instead of the value of color. 显示而不是颜色值。

————— ——————

How can I replace color by its value ? 我怎样才能更换color由它的value Can I use string interpolation? 我可以使用字符串插值吗?

试试: "<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM