diff --git a/spec/std/colorize_spec.cr b/spec/std/colorize_spec.cr index b0abfb580b09..772eae3f4d76 100644 --- a/spec/std/colorize_spec.cr +++ b/spec/std/colorize_spec.cr @@ -6,7 +6,7 @@ private def colorize(obj, *args) end private def with_color_wrap(*args) - with_color(*args).toggle(true) + Colorize.with(*args).toggle(true) end private class ColorizeToS @@ -129,6 +129,32 @@ describe "colorize" do colorize("hello", :red).inspect.should eq("\e[31m\"hello\"\e[0m") end + describe "with_color deprecated top-level method" do + it "without args" do + io = IO::Memory.new + with_color.red.toggle(true).surround(io) do + io << "hello" + with_color.green.toggle(true).surround(io) do + io << "world" + end + io << "bye" + end + io.to_s.should eq("\e[31mhello\e[0;32mworld\e[0;31mbye\e[0m") + end + + it "with args" do + io = IO::Memory.new + with_color(:red).toggle(true).surround(io) do + io << "hello" + with_color(:green).toggle(true).surround(io) do + io << "world" + end + io << "bye" + end + io.to_s.should eq("\e[31mhello\e[0;32mworld\e[0;31mbye\e[0m") + end + end + it "colorizes with surround" do io = IO::Memory.new with_color_wrap.red.surround(io) do diff --git a/src/colorize.cr b/src/colorize.cr index 23cc5e494c57..1d6bf38e0a0e 100644 --- a/src/colorize.cr +++ b/src/colorize.cr @@ -135,14 +135,29 @@ module Colorize def self.reset(io = STDOUT) io << "\e[0m" if enabled? end + + # Helper method to use colorize with `IO`. + # + # ``` + # io = IO::Memory.new + # io << "not-green" + # Colorize.with.green.bold.surround(io) do + # io << "green and bold if Colorize.enabled" + # end + # ``` + def self.with + "".colorize + end end +@[Deprecated("Use `Colorize.with`")] def with_color - "".colorize + Colorize.with end +@[Deprecated("Use `Colorize.with.fore(color)`")] def with_color(color : Symbol) - "".colorize(color) + Colorize.with.fore(color) end module Colorize::ObjectExtensions diff --git a/src/compiler/crystal/exception.cr b/src/compiler/crystal/exception.cr index fcf845708337..7dcc8ea5cb35 100644 --- a/src/compiler/crystal/exception.cr +++ b/src/compiler/crystal/exception.cr @@ -56,7 +56,7 @@ module Crystal end def with_color - ::with_color.toggle(@color) + Colorize.with.toggle(@color) end def replace_leading_tabs_with_spaces(line) @@ -126,7 +126,7 @@ module Crystal size ||= 0 io << '\n' io << (" " * (offset + column_number - 1)) - with_color.green.bold.surround(io) do + Colorize.with.green.bold.surround(io) do io << '^' if size > 0 io << ("-" * (size - 1)) diff --git a/src/compiler/crystal/tools/print_hierarchy.cr b/src/compiler/crystal/tools/print_hierarchy.cr index f789335ca966..2c6a1810e0ef 100644 --- a/src/compiler/crystal/tools/print_hierarchy.cr +++ b/src/compiler/crystal/tools/print_hierarchy.cr @@ -263,7 +263,7 @@ module Crystal end def with_color - ::with_color.toggle(@program.color?) + Colorize.with.toggle(@program.color?) end end