From a40d3debe8c83498b91150e2846d1f61d763189e Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Tue, 4 Aug 2020 16:59:40 +0800 Subject: [PATCH] Improve perf of `ActionView::Helpers::TextHelper#excerpt` for large strings. --- .../lib/action_view/helpers/text_helper.rb | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index 980a89a7b6..9d98f913ef 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "active_support/core_ext/string/filters" +require "active_support/core_ext/string/access" require "active_support/core_ext/array/extract_options" module ActionView @@ -467,18 +468,25 @@ module ActionView radius = options.fetch(:radius, 100) omission = options.fetch(:omission, "...") - part = part.split(separator) - part.delete("") - affix = part.size > radius ? omission : "" - - part = if part_position == :first - drop_index = [part.length - radius, 0].max - part.drop(drop_index) - else - part.first(radius) + if separator != "" + part = part.split(separator) + part.delete("") end - return affix, part.join(separator) + affix = part.length > radius ? omission : "" + + part = + if part_position == :first + part.last(radius) + else + part.first(radius) + end + + if separator != "" + part = part.join(separator) + end + + return affix, part end end end