crystal icon indicating copy to clipboard operation
crystal copied to clipboard

Add `Colorize::Object#print`

Open devnote-dev opened this issue 1 year ago • 2 comments

Quite simply, this method would print the ANSI codes to an optional IO (similar to how to_s operates). My primary use case for this is using colorize in regex expressions. At present, there aren't any good ways to handle colorize with regexes, especially when it comes to backreferences. For example, there's no way to use colorize with String#gsub:

require "colorize"

Colorize.enabled = false # not that this would do anything anyway

"foo|bar|baz".gsub(/\|(.+)\|/, "|\e[31m\\1\e[0m|") # => prints "foo|bar|baz" with "bar" in red

With this new method, it would allow for the following:

require "colorize"

Colorize.enabled = false

"foo|bar|baz".gsub(
  /\|(.+)\|/,
  "|#{Colorize.with.red.print}\\1#{Colorize.with.default.print}|"
) # => prints "foo|bar|baz" without colour/ANSI codes

devnote-dev avatar Oct 12 '24 01:10 devnote-dev

There's no need for another method. What you're looking for is the #gsub with a block.

Sija avatar Oct 12 '24 09:10 Sija

@Sija I presume you'r referring to something like "foo|bar|baz".gsub(/\|(.+)\|/) { |match| match.colorize(:red) }? That's not even necessary the use case from OP can be achieved directly: "foo|bar|baz".gsub(/\|(.+)\|/, "|#{"\\1".colorize(:red)}|").

Apart from this specific use case, I think it might still be useful to offer a method to get the escape sequence of a specific Colorize::Object.

straight-shoota avatar Oct 12 '24 12:10 straight-shoota

The choice of #print in the PR is confusing. It's reminiscent of IO#print but doesn't print and the "str".colorize.print feels like a #to_s that would include the string + ANSI escapes but it only returns the ansi escape...

Maybe #ansi_escape_code or #ansi_code (or something else) would be a bit more self-explanatory?

ysbaddaden avatar Dec 03 '24 13:12 ysbaddaden