Ruby链接为字符串中的URL

前端之家收集整理的这篇文章主要介绍了Ruby链接为字符串中的URL前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有一些关于使用正则表达式链接文本的帖子.最受欢迎的 is this post.

不过我的规格有点棘手:

  1. describe TextFormatter do
  2.  
  3. def l(input)
  4. TextFormatter.gsub_links!(input){|link| "!!#{link}!!"}
  5. end
  6.  
  7. it "should detect simple links" do
  8. l("http://www.cnn.com").should == "!!http://www.cnn.com!!"
  9. end
  10.  
  11. it "should detect multi links" do
  12. l("http://www.cnn.com http://boats.com?help.asp").should == "!!http://www.cnn.com!! !!http://boats.com?help.asp!!"
  13. end
  14.  
  15. it "should compensate for parans properly" do
  16. l("(http://this.is?hello_world)").should == "(!!http://this.is?hello_world!!)"
  17. end
  18.  
  19. it "should ignore existing links" do
  20. s = "<A HREF='http://sam.com'> http://sam.com </A>"
  21. l(s.dup).should == s
  22. end
  23.  
  24. it "should allow parans" do
  25. l("http://sam.com.au?(red)").should == "!!http://sam.com.au?(red)!!"
  26. end
  27.  
  28. end

任何想法如何实现毛茸茸的正则表达式:

这是我到目前为止的地方(它未通过2次测试):

  1. def gsub_links!(input)
  2. regex = /https?\:\/\/[\-\w+&@#\/%?=~\(\)\|!:,.;]*[\-\w+&@#\/%=~_\(\)|]/
  3. input.gsub!(regex) { |link|
  4. yield link
  5. }
  6. end

解决方法

我可能会错过一些背景,但为什么重新发明轮子?你在actionpack中尝试过auto_link吗?
  1. $gem install actionpack
  2.  
  3. $irb -f --prompt simple
  4. >> require 'action_view'
  5. >> include ActionView::Helpers
  6.  
  7. >> auto_link("abc http://google.com xyz")
  8. => "abc <a href=\"http://google.com\">http://google.com</a> xyz"
  9. >> auto_link("abc <a href='http://google.com'>google</a> xyz")
  10. => "abc <a href='http://google.com'>google</a> xyz"

猜你在找的Ruby相关文章