Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Colorize::Object#print #15079

Open
devnote-dev opened this issue Oct 12, 2024 · 3 comments · May be fixed by #15113
Open

Add Colorize::Object#print #15079

devnote-dev opened this issue Oct 12, 2024 · 3 comments · May be fixed by #15113

Comments

@devnote-dev
Copy link
Contributor

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
@Sija
Copy link
Contributor

Sija commented Oct 12, 2024

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

@straight-shoota
Copy link
Member

@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.

@devnote-dev devnote-dev linked a pull request Oct 21, 2024 that will close this issue
@ysbaddaden
Copy link
Contributor

ysbaddaden commented Dec 3, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants