3
0

More than 3 years have passed since last update.

【コピペだけでできる】Rails 超簡単 フォームのURLをハイパーリンク化する方法

Last updated at Posted at 2021-07-09

はじめに

筆者は 大学生限定 プログラミングコミュニティ 『GeekSalon』で活動している者です!
もし少しでも興味がありましたら、ぜひお話を聞きにきてくださいね♪

では本題。某SNSサイトなどで、入力フォームに打ち込んだURLが、ただの文字列としてではなく、リンクとして送信されることに対して不思議に思ったことがある人も多いのではないでしょうか?  
多分、多くないですね、、、^^;

今回は、それをコピペだけで実装できちゃうように紹介いたします。解説などは気が向いたらつけます。。。

前提

簡単な投稿機能は作成済みであること

こちらをコピペしましょう!

app/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
app/viwes/tweets/index.html.erb
  <% @twee.each do |t| %>
    <div class="tweet">
      <%= text_url_to_link((h(t.body).html_safe)).html_safe %>   # ←t.bodyのところは自分用に変更してね^^
    </div>
  <% end %>
end

※text_areaの改行をそのまま反映させたい場合

app/viwes/tweets/index.html.erb
  <% @twee.each do |t| %>
    <div class="tweet">
      <%= text_url_to_link(safe_join((h(t.body)).split("\n"),tag(:br))).html_safe %>   # ここが変わるよ^^
    </div>
  <% end %>
end

おしまい♪

いかがでしたでしょうか?
仕組みなどが気になったら、とりあえずググってみてくださいまし。

それではバイちゃーーー(^^)/~~~

3
0
1

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
3
0