Created
July 20, 2021 20:58
-
-
Save pboling/7860d75d4e3d3030e5f9ea4f011bae9a to your computer and use it in GitHub Desktop.
Colorized ansi_highlight
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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