Module: StringMagic::Formatting::Highlighting
- Included in:
- String, StringMagic
- Defined in:
- lib/string_magic/formatting/highlighting.rb
Instance Method Summary collapse
-
#highlight(phrases, tag: 'mark', css_class: nil, case_sensitive: true) ⇒ Object
———————————————————— Generic phrase highlighting ————————————————————.
-
#highlight_urls(tag: 'a', css_class: nil, target: nil) ⇒ Object
———————————————————— Auto-link / highlight URLs ————————————————————.
-
#remove_highlights(tag = nil) ⇒ Object
———————————————————— Remove previously added highlighting ————————————————————.
Instance Method Details
#highlight(phrases, tag: 'mark', css_class: nil, case_sensitive: true) ⇒ Object
Generic phrase highlighting
highlight(%w[ruby rails], tag: ‘span’,
css_class: 'hit', case_sensitive: false)
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/string_magic/formatting/highlighting.rb', line 13 def highlight(phrases, tag: 'mark', css_class: nil, case_sensitive: true) return '' if empty? phrases = Array(phrases).compact.reject(&:empty?) return self if phrases.empty? klass = css_class ? %( class="#{css_class}") : '' esc = phrases.sort_by(&:length).reverse.map { |p| Regexp.escape(p) } regex = Regexp.union(esc) regex = Regexp.new(regex.source, Regexp::IGNORECASE) unless case_sensitive gsub(regex) { |m| "<#{tag}#{klass}>#{m}</#{tag}>" } end |
#highlight_urls(tag: 'a', css_class: nil, target: nil) ⇒ Object
Auto-link / highlight URLs
highlight_urls(css_class: ‘link’, target: ‘_blank’)
50 51 52 53 54 55 56 57 58 |
# File 'lib/string_magic/formatting/highlighting.rb', line 50 def highlight_urls(tag: 'a', css_class: nil, target: nil) return '' if empty? klass = css_class ? %( class="#{css_class}") : '' tgt = target ? %( target="#{target}") : '' url_re = %r{https?://[^\s<>"']+}i gsub(url_re) { |url| %(<#{tag} href="#{url}"#{klass}#{tgt}>#{url}</#{tag}>) } end |
#remove_highlights(tag = nil) ⇒ Object
Remove previously added highlighting
remove_highlights # strips ALL html tags remove_highlights(‘mark’) # strips only <mark>…</mark>
34 35 36 37 38 39 40 41 42 |
# File 'lib/string_magic/formatting/highlighting.rb', line 34 def remove_highlights(tag = nil) return '' if empty? if tag gsub(/<#{Regexp.escape(tag)}[^>]*>(.*?)<\/#{Regexp.escape(tag)}>/im, '\1') else gsub(/<[^>]+>/, '') end end |