1
0

More than 1 year has passed since last update.

【Rails】URLにaタグを付ける

Last updated at Posted at 2022-07-08

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]
httporhttpsの正規表現を検索し、文字列にして返します
受け取った文字列を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 %>
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0