instance method truncate_bytes

Ruby on Rails 6.0.6

Since v6.0.6

Available in: v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

truncate_bytes(truncate_at, omission: "…")

Truncates text to at most bytesize bytes in length without breaking string encoding by splitting multibyte characters or breaking grapheme clusters (“perceptual characters”) by truncating at combining characters.

>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".size
=> 20
>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".bytesize
=> 80
>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".truncate_bytes(20)
=> "🔪🔪🔪🔪…"

The truncated text ends with the :omission string, defaulting to “…”, for a total length not exceeding bytesize.

Parameters

truncate_at req
omission key = "…"
Source
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 95
  def truncate_bytes(truncate_at, omission: "…")
    omission ||= ""

    case
    when bytesize <= truncate_at
      dup
    when omission.bytesize > truncate_at
      raise ArgumentError, "Omission #{omission.inspect} is #{omission.bytesize}, larger than the truncation length of #{truncate_at} bytes"
    when omission.bytesize == truncate_at
      omission.dup
    else
      self.class.new.tap do |cut|
        cut_at = truncate_at - omission.bytesize

        scan(/\X/) do |grapheme|
          if cut.bytesize + grapheme.bytesize <= cut_at
            cut << grapheme
          else
            break
          end
        end

        cut << omission
      end
    end
  end

Defined in activesupport/lib/active_support/core_ext/string/filters.rb line 95 · View on GitHub · Improve this page · Find usages on GitHub

Defined in String

Type at least 2 characters to search.

↑↓ navigate · open · esc close