开发者

Converting links into anchors when displaying data in Rails

开发者 https://www.devze.com 2023-01-26 19:46 出处:网络
So I have some textual data which contains links, now what is the proper way to convert them into an开发者_开发知识库chors when that data is being displayed.

So I have some textual data which contains links, now what is the proper way to convert them into an开发者_开发知识库chors when that data is being displayed.

The one way that I see is to do smth like this raw(urlize(h(data)))... Maybe there is better way?

P.S. I don't want to use redcloth


You can write a method that implements the Daring Fireball inspired link matcher:

class String
  def urlify
    gsub(%r{\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))}u) do |s|
      %Q{<a href="#{s}">#{s}</a>}
    end.html_safe
  end
end

This will link anything prefixed with the proper protocol like http:// or mailto: though care should be taken to skip or strip javascript: links.


We can use the auto_link gem here

0

精彩评论

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