开发者

In a Rails 3 view, how do I detect an URL in a display string and format it as a link to that URL?

开发者 https://www.devze.com 2023-02-09 16:56 出处:网络
I have us开发者_Python百科er generated comments on my site.If a user adds an URL in their comment, I\'d like it to be formatted as a link and actually link to that URL.How do I do that?Rails has an au

I have us开发者_Python百科er generated comments on my site. If a user adds an URL in their comment, I'd like it to be formatted as a link and actually link to that URL. How do I do that?


Rails has an auto_link text helper.

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"


In rails 3.1 auto_link has ben removed, its now a standalone gem: https://github.com/tenderlove/rails_autolink


You could also use the "auto_html" gem, see https://github.com/dejan/auto_html.

Disclaimer: Haven't used it myself yet, but it looks like it could do what you want.


I'd also recommend thinking about something like Markdown for your comments. Then you can let the Markdown engine worry about stuff like this for you.


First, you should define a regexp matching http strings, for example

IPv4_PART = /\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]/  # 0-255
REGEXP = %r{
    https?://                                                    # http:// or https://
    ([^\s:@]+:[^\s:@]*@)?                                        # optional username:pw@
    ( (([^\W_]+\.)*xn--)?[^\W_]+([-.][^\W_]+)*\.[a-z]{2,6}\.? |  # domain (including Punycode/IDN)...
        #{IPv4_PART}(\.#{IPv4_PART}){3} )                        # or IPv4
    (:\d{1,5})?                                                  # optional port
    ([/?]\S*)?                                                   
}iux

then, suppose the comment body is str, you do:

str.gsub(REGEXP) do |m|
    link_to m, m
end
0

精彩评论

暂无评论...
验证码 换一张
取 消