Skip to content

Commit

Permalink
Optimize TextHelper.highlight for large inputs
Browse files Browse the repository at this point in the history
Co-authored-by: Jonathan Hefner <jonathan@hefner.pro>
  • Loading branch information
fatkodima and jonathanhefner committed Feb 10, 2023
1 parent e184d33 commit f2cb36f
Showing 1 changed file with 13 additions and 10 deletions.
23 changes: 13 additions & 10 deletions actionview/lib/action_view/helpers/text_helper.rb
Expand Up @@ -139,16 +139,19 @@ def highlight(text, phrases, options = {}, &block)
if text.blank? || phrases.blank?
text || ""
else
match = Array(phrases).map do |p|
Regexp === p ? p.to_s : Regexp.escape(p)
end.join("|")

if block_given?
text.gsub(/(#{match})(?![^<]*?>)/i, &block)
else
highlighter = options.fetch(:highlighter, '<mark>\1</mark>')
text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
end
patterns = Array(phrases).map { |phrase| Regexp === phrase ? phrase : Regexp.escape(phrase) }
pattern = /(#{patterns.join("|")})/i
highlighter = options.fetch(:highlighter, '<mark>\1</mark>') unless block

text.scan(/<[^>]*|[^<]+/).each do |segment|
if !segment.start_with?("<")
if block
segment.gsub!(pattern, &block)
else
segment.gsub!(pattern, highlighter)
end
end
end.join
end.html_safe
end

Expand Down

0 comments on commit f2cb36f

Please sign in to comment.