6

There have been a few posts about linkifying text using a regex. The most popular is this post.

However my spec is a little more tricky:

describe TextFormatter do 

  def l(input) 
    TextFormatter.gsub_links!(input){|link| "!!#{link}!!"}
  end

  it "should detect simple links" do
    l("http://www.cnn.com").should == "!!http://www.cnn.com!!"
  end

  it "should detect multi links" do
    l("http://www.cnn.com http://boats.com?help.asp").should == "!!http://www.cnn.com!! !!http://boats.com?help.asp!!"
  end

  it "should compensate for parans properly" do 
    l("(http://this.is?hello_world)").should == "(!!http://this.is?hello_world!!)"
  end

  it "should ignore existing links" do 
    s = "<A HREF='http://sam.com'> http://sam.com </A>"
    l(s.dup).should == s
  end

  it "should allow parans" do 
    l("http://sam.com.au?(red)").should == "!!http://sam.com.au?(red)!!"
  end

end

Any ideas how to implement the hairy Regex:

This is where I am so far (it fails 2 tests):

  def gsub_links!(input)
    regex = /https?\:\/\/[\-\w+&@#\/%?=~\(\)\|!:,.;]*[\-\w+&@#\/%=~_\(\)|]/
    input.gsub!(regex) { |link|
      yield link
    }
  end
Community
  • 1
  • 1
Sam Saffron
  • 128,308
  • 78
  • 326
  • 506

1 Answers1

14

I might be missing some context, but why re-invent the wheel? Have you tried auto_link in actionpack?

$ gem install actionpack

$ irb -f --prompt simple
>> require 'action_view'
>> include ActionView::Helpers

>> auto_link("abc http://google.com xyz")
=> "abc <a href=\"http://google.com\">http://google.com</a> xyz"
>> auto_link("abc <a href='http://google.com'>google</a> xyz")
=> "abc <a href='http://google.com'>google</a> xyz"
Ryan McGeary
  • 235,892
  • 13
  • 95
  • 104
  • yerp, auto link seems to pass all my tests ... thanks for pointing it out – Sam Saffron Sep 18 '09 at 04:07
  • why it might not work in app? I'm getting an error "wrong number of arguments (2 for 1) file: tag_helper.rb location: tag_options line: 113" while trying to do that. It works perfectly in console though – Arty Dec 07 '10 at 22:55
  • 4
    `auto_link` is gone from Rails since 3.1. See http://stackoverflow.com/questions/6418710/replacing-the-auto-link-method-in-ruby-on-rails-3-1 for an updated answer. – Thilo Jul 27 '12 at 09:30