instance method excerpt

Ruby on Rails 7.0.10

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, options = {})

Extracts the first occurrence of phrase plus surrounding text from text. An omission marker is prepended / appended if the start / end of the result does not coincide with the start / end of text. The result is always stripped in any case. Returns nil if phrase isn’t found.

Options

:radius

The number of characters (or tokens — see :separator option) around phrase to include in the result. Defaults to 100.

:omission

The marker to prepend / append when the start / end of the excerpt does not coincide with the start / end of text. Defaults to "...".

:separator

The separator between tokens to count for :radius. Defaults to "", which treats each character as a token.

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"

excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1)
# => "...a very beautiful..."

Parameters

text req
phrase req
options opt = {}
Source
# File actionview/lib/action_view/helpers/text_helper.rb, line 231
      def excerpt(text, phrase, options = {})
        return unless text && phrase

        separator = options.fetch(:separator, nil) || ""
        case phrase
        when Regexp
          regex = phrase
        else
          regex = /#{Regexp.escape(phrase)}/i
        end

        return unless matches = text.match(regex)
        phrase = matches[0]

        unless separator.empty?
          text.split(separator).each do |value|
            if value.match?(regex)
              phrase = value
              break
            end
          end
        end

        first_part, second_part = text.split(phrase, 2)

        prefix, first_part   = cut_excerpt_part(:first, first_part, separator, options)
        postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)

        affix = [first_part, separator, phrase, separator, second_part].join.strip
        [prefix, affix, postfix].join
      end

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