LoginSignup
1
0

More than 5 years have passed since last update.

ユーザの入力した文字列を画面表示用に加工するためのヘルパメソッド

Last updated at Posted at 2018-07-18

やること

任意の文字列に次の処理を施します。

  • 文字列中の HTML 文字列を画面にそのまま表示できるようにエスケープする。
  • 文字列中の改行コード \n を br 要素に変換する。
  • 文字列中の URL を a 要素に変換する。
    • Rinku という Gem を使います。

実装

app/helpers/application_helper.rb
def str_to_html(str)
  str
    .yield_self { |s| ERB::Util.html_escape(s) }
    .gsub("\n", tag.br)
    .yield_self { |s| Rinku.auto_link(s, :all, 'target="_blank"') }
    .html_safe
end

使用例

article.update(body: <<~TEXT)
  リズと青い鳥 http://liz-bluebird.com/ 見てね!
  夏紀先輩が相変わらずかわいい <span role="img" aria-label="heart">❤️</span>
TEXT
<%= article.body %>

ss01.png

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