LoginSignup
1
1

More than 3 years have passed since last update.

【Rails】URLテキストにaタグを自動でつける

Posted at

はじめに

ユーザーがフォームに投稿したURLテキストに自動でaタグをつけて表示できたらなーーと調べていたら、uriライブラリーのおかげでとても簡単にできたので、備忘録としてまとめます。

uriライブラリーを読み込む

Rubyの標準ライブラリーとして'uri'というURIを扱う標準ライブラリ-があるので、読み込みます。
https://docs.ruby-lang.org/ja/latest/class/URI.html

app/helpers/application_helper.rb
require "uri"

ヘルパーメソッドを作成

uriライブラリーを読み込んだapplication_helper.rbでメソッドを作成します。

app/helpers/application_helper.rb
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
  1. URI.extractで、httpもしくはhttpsで始まるtextを url として取り出し、sub_text という変数に代入

2.
gsub!メソッドで textをsub_textに変換

3.
変換したtextを返す

該当のviewに表示させる

URLテキストにaタグをつけて表示させたい部分に、以下のように先ほど作成したメソッドを使用して、表示させます。

app/views/sample.html.erb
<%= text_url_to_link(h(該当する変数)).html_safe %>

これで、無事にURLテキストに自動でaタグをつけて表示してくれるようになります。

1
1
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
1