Module: Translighterate
- Defined in:
- lib/translighterate.rb,
lib/translighterate/version.rb
Constant Summary collapse
- VERSION =
"0.3.0"
Class Method Summary collapse
Class Method Details
.highlight(text, phrases, options = {}) ⇒ Object
Copied (and modified!) from
https://github.com/rails/rails/blob/495ef4124e292dcc7062e3e1f04f623053113101/actionview/lib/action_view/helpers/text_helper.rb#L130
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/translighterate.rb', line 8 def self.highlight(text, phrases, = {}) text = sanitize(text) if .fetch(:sanitize, true) if text.blank? || phrases.blank? text || "" else match = Array(phrases).map do |p| Regexp === p ? p.to_s : Regexp.escape(p) end.join('|') # Transliteration trick from: # https://github.com/cubing/worldcubeassociation.org/issues/238#issuecomment-234702800 transliterated = text.chars.map { |ch| transliterate_char(ch) }.join previous_match_end_index = 0 result = "" transliterated.scan(/(#{match})(?![^<]*?>)/i) do match_range = $~.offset(0) result += text[previous_match_end_index...match_range[0]] original_text_found = text[Range.new(*match_range, true)] previous_match_end_index = match_range[1] result += if block_given? yield original_text_found else highlighter = .fetch(:highlighter, '<mark>\1</mark>') highlighter.gsub(/\\1/, original_text_found) end end result += text[previous_match_end_index..-1] end.html_safe end |