RailsはURLテキストを入れて投稿しても、自動的にリンクを付与してくれません( ꒪⌓꒪Ⅲ)
ユーザーに全く優しくないので、
URLリンク先に遷移できるようにしましょう!
まずは、ヘルパーにメソッドを書いていきます。
ヘルパーは、application_helper.rb or コントローラー名_helper.rbに記述可能です。
今回は、複数箇所で使用したいので、application_helper.rbに書いていきます!
helpers/application_helper.rb
module ApplicationHelper
require "uri"
def text_url_to_link text
URI.extract(text, ['http','https']).uniq.each do |url|
sub_text = ""
sub_text << "<a href=" << url << " target=\"_blank\">" << url << "</a>"
text.gsub!(url, sub_text)
end
return text
end
end
URI.extractメソッド
extract(str, schemes) -> [String]
http
orhttps
の正規表現を検索し、文字列にして返します
受け取った文字列をeachで処理します。
インスタンスメソッド gsub
取得したURLテキストをてaタグに変換してくれます。
詳しくはこちら→参照:instance method String#gsub
ちなみにこれってなんて読むのでしょうか?グスブ?(*゚ロ゚)ン?
最後に任意のビューに下記のコードを追加して完了です!
ビューでヘルパーメソッドを呼び出すときは、メソッド名そのままで呼び出しが可能です。
※ControllerやModelは呼び出し方法が違うので注意です。
views/posts/show.html.erb
<%= text_url_to_link((h(@post.text).html_safe)).html_safe %>