Class: ReeText::Highlight

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_text/package/ree_text/functions/highlight.rb

Constant Summary collapse

DEFAULTS =
{
  highlighter: '<mark>\1</mark>',
  sanitize: true,
}.freeze

Instance Method Summary collapse

Instance Method Details

#call(text, phrases = nil, **opts, &block) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/ree_lib/packages/ree_text/package/ree_text/functions/highlight.rb', line 54

def call(text, phrases = nil, **opts, &block)
  options = DEFAULTS.merge(opts)

  text = sanitize_html(text) if options[:sanitize]

  if !phrases
    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[:highlighter]
      text.gsub(/(#{match})(?![^<]*?>)/i, highlighter)
    end
  end
end