LoginSignup
67
59

More than 5 years have passed since last update.

[Ruby][Rails]テキスト内のURLをaタグに書き換える

Last updated at Posted at 2014-04-14

RailsでWebページ上にテキストを表示するときにときに
自動でテキスト内のURLをaタグに書き換えてくれたら楽だなーと思って調べてみた。

application_helper.rb

require "uri"

def text_url_to_link text

  URI.extract(text, ['http']).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というライブラリを使ってテキスト内からURLを取得する。

application_helper.rb
require "uri"
application_helper.rb
URI.extract(text)

(追記 2014/4/18)
KitaitiMakotoさんにコメントいただきました。

application_helper.rb
URI.extract(text)

だとmailtoftpなどのスキームも抜き出してしまうようです。
なので、第二引数を追加

application_helper.rb
URI.extract(text, ['http'])

2.取得したURL(同じのを一気にやるためユニークにする)を書き換える

application_helper.rb
URI.extract(text, ['http']).uniq.each do |url|
    sub_text = ""
    sub_text << "<a href=" << url << " target=\"_blank\">" << url << "</a>"

    text.gsub!(url, sub_text)
  end

sub_textっていうのが書き換え後のテキスト。
aタグ作って今回は全て別のタブで開くために target="_blank" を追加

3.書き換えたテキストを戻り値として返す

application_helper.rb
return text

4.Viewから読み出す

url.html.erb

<%= text_url_to_link(h(@text)).html_safe %>

これで@textに含まれるURLをaタグに自動で書き換えてHTMLで表示することができる。
h()とか、.html_safeとかなんだよってひとはこちら。

[Rails]ERBのエスケープを自在に扱おうぜ

67
59
9

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
67
59