module Nuggets::String::HighlightMixin
Public Instance Methods
highlight(needle[, prefix[, postfix]]) → new_string
click to toggle source
Highlight occurrences of needle
(String(s) and/or Regexp(s)) in str by surrounding them with prefix
and postfix
.
# File lib/nuggets/string/highlight_mixin.rb 36 def highlight(needle, prefix = '|', postfix = prefix) 37 offsets = [] 38 39 Array(needle).each { |arg| 40 while index = index(arg, index || 0) 41 offsets << [index, index += ($& || arg).length] 42 end 43 } 44 45 flattened = [current = offsets.sort!.shift] 46 47 offsets.each { |offset| 48 i1, j1 = current 49 i2, j2 = offset 50 51 i2 > j1 ? flattened << current = offset : 52 j2 > j1 ? current[-1] = j2 : nil 53 } 54 55 dup.tap { |result| flattened.reverse_each { |i, j| 56 result.insert(j, postfix).insert(i, prefix) 57 } } 58 end