Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Colorized ansi_highlight
# frozen_string_literal: true
require "colorized_string"
String.class_eval do
# Adapted from the Rails highlight text helper.
# http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-highlight
#
# NOT FOR USE WITH HTML (use the Rails standard one for that)
#
def ansi_highlight(*phrases)
match = phrases.map do |p|
Regexp === p ? p.to_s : Regexp.escape(p) # rubocop:disable Style/CaseEquality
end.join("|")
if block_given?
gsub(/(#{match})/i) { |found| yield ColorizedString[found] }
else
gsub(/(#{match})/i) { |found| ColorizedString[found].red.on_black }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment