Skip to content

Instantly share code, notes, and snippets.

@pboling
Created July 20, 2021 20:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pboling/7860d75d4e3d3030e5f9ea4f011bae9a to your computer and use it in GitHub Desktop.
Save pboling/7860d75d4e3d3030e5f9ea4f011bae9a to your computer and use it in GitHub Desktop.
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