instance method truncate

Ruby on Rails 2.2.3

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

truncate(text, *args)

Truncates a given text after a given :length if text is longer than :length (defaults to 30). The last characters will be replaced with the :omission (defaults to “…”).

Examples

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

truncate("Once upon a time in a world far far away", :length => 14)
# => Once upon a...

truncate("And they found that many people were sleeping better.", :length => 25, "(clipped)")
# => And they found that many (clipped)

truncate("And they found that many people were sleeping better.", :omission => "... (continued)", :length => 15)
# => And they found... (continued)

You can still use truncate with the old API that accepts the length as its optional second and the ellipsis as its optional third parameter:

truncate("Once upon a time in a world far far away", 14)
# => Once upon a time in a world f...

truncate("And they found that many people were sleeping better.", 15, "... (continued)")
# => And they found... (continued)

Parameters

text req
args rest
Source
# File actionpack/lib/action_view/helpers/text_helper.rb, line 70
      def truncate(text, *args)
        options = args.extract_options!
        unless args.empty?
          ActiveSupport::Deprecation.warn('truncate takes an option hash instead of separate ' +
            'length and omission arguments', caller)

          options[:length] = args[0] || 30
          options[:omission] = args[1] || "..."
        end
        options.reverse_merge!(:length => 30, :omission => "...")

        if text
          l = options[:length] - options[:omission].mb_chars.length
          chars = text.mb_chars
          (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s
        end
      end

Defined in actionpack/lib/action_view/helpers/text_helper.rb line 70 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::TextHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close