14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsのtruncateの使い方

Posted at

truncateとは

文字列を切り捨てて省略表示します。

使い方はこちらの記事を参考にしました。
Rails - 長い文字列を省略して表示する

2つある?

どうやらString#truncateとTextHelperとしてのtruncateがあるらしい…

string.rb
'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."

helper.rb
truncate("Once upon a time in a world far far away")
# => "Once upon a time in a world..."

何が違うの?

困ったときはソースコードを見よう:innocent::sparkles:

  • String#truncateの実装
String#truncate.rb
def truncate(truncate_at, options = {})
  return dup unless length > truncate_at

  omission = options[:omission] || '...'
  length_with_room_for_omission = truncate_at - omission.length
  stop = \
    if options[:separator]
      rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
    else
      length_with_room_for_omission
    end

  "#{self[0, stop]}#{omission}"
end

link:github

  • Texthelperの実装
texthelper.rb
def truncate(text, options = {}, &block)
  if text
    length  = options.fetch(:length, 30)

    content = text.truncate(length, options)
    content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content)
    content << capture(&block) if block_given? && text.length > length
    content
   end
end

link:github

あ、これTexthelperの内部でString#truncateが呼ばれてるやつだ…!

なのでTexthelperの方は

  1. 使えるオプションが多い(:escape)
  2. ブロックで使うことができる

といった違いがありそうです。

14
12
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
14
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?