LoginSignup
3
1

More than 1 year has passed since last update.

[Rails]Rinkuを使って、URLを自動的にリンクにする

Posted at

はじめに

本記事はURLを自動的にaタグに変換できるRinkuについて解説したものです。
これを使えば記事系や投稿系のアプリケーションの投稿データなどのURLをリンクにすることが可能です。
記事の最後には改行を出力するsimple_formatと組み合わせた記述の仕方も解説しています。

ドキュメント(github) → https://github.com/vmg/rinku

インストール

以下を入力してbundle installします

Gemfile
gem 'rinku'

使い方

Rinkuは以下のような形式で書きます

<%= raw Rinku.auto_link(h(変数)) %>
<%= raw Rinku.auto_link(h("http://www.foo.com"))%>

上記のようにすると以下のように出力されます。

<a href="http://www.foo.com">http://www.foo.com</a>

またこのURLを外部リンクにしたい場合は以下のようにします。

<%= Rinku.auto_link("http://www.foo.com" ,:all, 'target="_blank"')%>

'target="_blank"'のように文字列として指定することで外部リンクとして実装できます。

(応用) simple_formatと組み合わせる

simple_formatと組み合わせることで引数に指定したオブジェクトの改行を出力することができます。

<%= row Rinku.auto_link(simple_format(h(変数)) ,:all, 'target="_blank"')%>
3
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
3
1