0

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?

2 Answers 2

1

Try: "<span class=\"highlight-#{color}\">\1</span>"

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a lot. That's what I thought but I must have tried it wrong the first time. I will accept your answer as soon as I can.
Hi. I am sorry, I had to unaccept your answer, because it does not seem to actually work, as you can see in the UPDATE section of my question. I am glad to accept it again once I can fix my issue ;) Thanks.
See my revised answer.
1

Try it with a block, it's easier to deal with:

string.gsub(/https?:\/\/\S+/){|link| "<span class=\"highlight-#{color}\">#{link}</span>"}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.