In my Rails 4 app, I have the following post helper:
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.
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:
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
.
Instead, I would like to link_highlight(string, blue)
to apply the highlight-blue
class to the string.
—————
UPDATE: I tried the solution offered by @dankohn but it is actually not working.
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
? Can I use string interpolation?
Try: "<span class=\"highlight-#{color}\">\1</span>"