使用link_to和gsub创建链接

时间:2014-06-25 22:08:27

标签: ruby-on-rails ruby link-to gsub

我有一段文字正在输入文本区域,如果任何文字符合URI.regexp,我需要在target: '_blank'标记上的a上激活该链接textarea。

这是我目前的代码。我也尝试使用.match来纠正

def comment_body(text)
  text = auto_link(text)

  text.gsub!(URI.regexp) do |match|
    link_to(match, match, target: '_blank')
  end
end

输出:

我认为

https://facebook.com">https://facebook.com

在经过检查的HTML中

<a href="<a href=" https:="" facebook.com"="" target="_blank">https://facebook.com</a>

gsub docs中,它表示元字符将按字面解释,这就是我认为在这里弄乱我的。

有关如何正确构建此网址的任何提示?

谢谢!

3 个答案:

答案 0 :(得分:1)

auto_link宝石完全符合您的需要。

您可以查看其代码以了解它如何使用gsub。

答案 1 :(得分:0)

编辑:此解决方案需要将清理设置为false,这通常不是一个好主意!

我找到了一个不使用auto_link的解决方案(我也使用Rails 5)。我知道这是一个古老的线程,但我花了一些时间试图找到一个允许插入target =“_ blank”的解决方案并找到了这个。在这里,我正在创建一个帮助程序,在文本框中搜索链接的文本,然后添加基本上使它们在视图中可链接。

def formatted_comment(comment)
    comment = comment.body

    URI.extract(comment, ['http', 'https']).each do |uri|
        comment = comment.gsub( uri, link_to(uri, uri, target: "_blank"))
    end

    simple_format(comment, {}, class: "comment-body", sanitize: false)
end

这里的关键是simple_format保持消毒,因此添加{}和sanitize:false非常重要。

***请注意,将sanitize设置为false可能会带来其他问题,例如允许javascript在评论中运行,但此解决方案将允许将target =“_ blank”插入到链接中。

答案 2 :(得分:-1)

使用带有后引用的简单gsub的一个解决方案是这样的:(您当然可以修改正则表达式以满足您的需求。)

str = 'here is some text about https://facebook.com and you really http://www.google.com should check it out.'

linked_str = str.gsub( /((http|https):\/\/(www.|)(\w*).(com|net|org))/, 
                         '<a href="\1" target="_blank">\4</a>' )

示例输出:

print linked_str
#=> here is some text about <a href="https://facebook.com" target="_blank">facebook</a> and you really <a href="http://www.google.com" target="_blank">google</a> should check it out.