在Rails 3视图中,如何检测显示字符串中的URL并将其格式化为该URL的链接?

Sam*_*erg 9 ruby-on-rails

我在我的网站上有用户生成的评论.如果用户在评论中添加了一个URL,我希望将其格式化为链接并实际链接到该URL.我怎么做?

Sim*_*tti 18

Rails有一个auto_link文本助手.

auto_link("Go to http://www.rubyonrails.org and say hello to david@loudthinking.com")
# => "Go to <a href=\"http://www.rubyonrails.org\">http://www.rubyonrails.org</a> and
#     say hello to <a href=\"mailto:david@loudthinking.com\">david@loudthinking.com</a>"

auto_link("Visit http://www.loudthinking.com/ or e-mail david@loudthinking.com", :link => :urls)
# => "Visit <a href=\"http://www.loudthinking.com/\">http://www.loudthinking.com/</a>
#     or e-mail david@loudthinking.com"
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用的是Rails 3.1+,请按照nikstep使用rails_autolink (2认同)

nik*_*tep 8

在rails 3.1中,auto_link已被删除,它现在是一个独立的宝石:https://github.com/tenderlove/rails_autolink