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, line 36
def highlight(needle, prefix = '|', postfix = prefix)
  offsets = []

  Array(needle).each { |arg|
    while index = index(arg, index || 0)
      offsets << [index, index += ($& || arg).length]
    end
  }

  flattened = [current = offsets.sort!.shift]

  offsets.each { |offset|
    i1, j1 = current
    i2, j2 = offset

    i2 > j1 ? flattened << current = offset :
    j2 > j1 ? current[-1] = j2 : nil
  }

  dup.tap { |result| flattened.reverse_each { |i, j|
    result.insert(j, postfix).insert(i, prefix)
  } }
end