instance method excerpt

Ruby on Rails 3.2.22.5

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

excerpt(text, phrase, *args)

Extracts an excerpt from text that matches the first instance of phrase. The :radius option expands the excerpt on each side of the first occurrence of phrase by the number of characters defined in :radius (which defaults to 100). If the excerpt radius overflows the beginning or end of the text, then the :omission option (which defaults to “…”) will be prepended/appended accordingly. The resulting string will be stripped in any case. If the phrase isn’t found, nil is returned.

Examples

excerpt('This is an example', 'an', :radius => 5)
# => ...s is an exam...

excerpt('This is an example', 'is', :radius => 5)
# => This is a...

excerpt('This is an example', 'is')
# => This is an example

excerpt('This next thing is an example', 'ex', :radius => 2)
# => ...next...

excerpt('This is also an example', 'an', :radius => 8, :omission => '<chop> ')
# => <chop> is also an example

You can still use excerpt with the old API that accepts the radius as its optional third and the ellipsis as its optional forth parameter:

excerpt('This is an example', 'an', 5)                   # => ...s is an exam...
excerpt('This is also an example', 'an', 8, '<chop> ')   # => <chop> is also an example

Parameters

text req
phrase req
args rest
Source
# File actionpack/lib/action_view/helpers/text_helper.rb, line 157
      def excerpt(text, phrase, *args)
        return unless text && phrase

        options = args.extract_options!
        unless args.empty?
          ActiveSupport::Deprecation.warn "Calling excerpt with radius and omission as arguments is deprecated. " \
          "Please call with :radius => #{args[0]}#{", :omission => '#{args[1]}'" if args[1]} instead.", caller

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

        phrase = Regexp.escape(phrase)
        return unless found_pos = text.mb_chars =~ /(#{phrase})/i

        start_pos = [ found_pos - options[:radius], 0 ].max
        end_pos   = [ [ found_pos + phrase.mb_chars.length + options[:radius] - 1, 0].max, text.mb_chars.length ].min

        prefix  = start_pos > 0 ? options[:omission] : ""
        postfix = end_pos < text.mb_chars.length - 1 ? options[:omission] : ""

        prefix + text.mb_chars[start_pos..end_pos].strip + postfix
      end

Defined in actionpack/lib/action_view/helpers/text_helper.rb line 157 · 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