2014-06-25 50 views
1

我有一個文本正文被送入textarea,如果任何文本匹配URI.regexp,我需要使該鏈接在文本區域a標記上的target: '_blank'處於活動狀態。創建link_to和gsub鏈接

這是我目前的代碼。我也試圖與.match這將correc

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它說元字符將被字面解釋,這是我相信這在我這裏搞砸了。

有關如何正確構建此URL的任何提示?

謝謝!

回答

1

auto_link寶石確實是你所需要的。

你可以看看它的代碼,看看它如何使用gsub。

+0

我上面有一行,'text = auto_link(text)'。這已經在使用中。編輯我的代碼以反映它 –

+0

如果您已經在使用它,只需傳遞選項以使'target =「_ blank」'像這樣:'auto_link(text,:all,:target =>「_blank」)' – San

-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. 
+0

不工作。由於某種原因,a標籤中沒有target =「_ blank」 –

+0

@Zack這怎麼可能?正好粘貼HTML輸出的內容。 – fyz

+0

和我最初的帖子一樣 –

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保持消毒,所以添加{}和消毒:false都很重要。

***請注意,將sanitize設置爲false可能會導致其他問題,如允許javascript在註釋中運行,但此解決方案將允許將target =「_ blank」插入到鏈接中。