LoginSignup
212
197

More than 5 years have passed since last update.

Rails - 長い文字列を省略して表示する

Last updated at Posted at 2015-02-19

モデルが属性として持っている長い文字列を省略して、「隣の客はよく柿食う...」のように表示したい。

こんな時は、モデル側で省略後の文字列を返すメソッドを定義して、ビューからそれを呼び出せば良いと考えてました。

app/models/hoge.rb
class Hoge < ActiveRecord::Base
  def short_description
    description[0, 9] + '...'
  end
end
app/views/hoge/index.html.erb
<%= @hoge.short_description %>

しかし、表示に関わることをモデルに書くのはどうなんだろうという気がして、ヘルパーメソッドを作った方がいいんじゃないかと思いました。
そして調べてみたら、truncateというメソッドを見つけました。

app/views/hoge/index.html.erb
<%= "This is a pen. That is a desk.".truncate(20) %>
<%# "This is a pen. Th..." %>

ActiveSupportでStringクラスに追加されたメソッドです。
オプションは以下のような感じです。

オプション 説明 デフォルト
:omission 省略された文字列の後ろにつける文字列 ...
:separator 区切り文字。中途半端なところで文字列が切れないようにする。 なし
app/views/hoge/index.html.erb
<%= "This is a pen. That is a desk.".truncate(24) %>
<%# "This is a pen. That i..." %>

<%= "This is a pen. That is a desk.".truncate(24, omission: '~~~') %>
<%# "This is a pen. That i~~~" %>

<%= "This is a pen. That is a desk.".truncate(24, separator: ' ') %>
<%= "This is a pen. That is a desk.".truncate(24, separator: /\s/) %>
<%# "This is a pen. That..." %>

<%= "This is a pen. That is a desk.".truncate(24, separator: '.') %>
<%# "This is a pen..." %>

ヘルパーメソッドにもありました。省略後の文字数がオプションになっています。

app/views/hoge/index.html.erb
<%= truncate(@hoge.description, length: 10) %>
オプション 説明 デフォルト
:length 省略後の文字列長 30
:omission 上と同じ ...
:separator 上と同じ なし
:escape HTMLエスケープ(falseを指定するとエスケープしない) true

ブロックを渡すと、ブロックの戻り値が、省略後文字列の末尾に追加されます。

app/views/hoge/index.html.erb
<%= truncate(@hoge.description) do %>
  <p>(省略されました。続きを読むには<%= link_to 'ここ', ... %>をクリックしてください。<p>
<% end %>
212
197
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
212
197