Skip to content

Commit

Permalink
Helpers::Text: Add .colorize(color, text, **opts)
Browse files Browse the repository at this point in the history
  • Loading branch information
joallard committed Dec 24, 2020
1 parent cbeab27 commit bf81539
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/pry/helpers/text.rb
Expand Up @@ -39,6 +39,22 @@ module Text
end
end

# Apply _color_ or style to _text_
#
# @param text [String]
# @param color [nil, Symbol] Color selected from `COLORS`
# @option bold [nil, true, false]
# @option faded [nil, true, false]
# @return [String] Text
def colorize(text, color = nil, bold: false, faded: false)
b = []
b << 1 if bold
b << 2 if faded
b << 0 if b.empty?

escape(text, b, COLORS[color.to_s])
end

# Escape _text_ with SGR escape _codes_
#
# @param text [String]
Expand Down
47 changes: 47 additions & 0 deletions spec/helpers/text_spec.rb
@@ -0,0 +1,47 @@
# frozen_string_literal: true

describe Pry::Helpers::Text do
describe ".colorize" do
include Pry::Helpers::Text

it "with color" do
expect(
colorize("Pry", :blue)
).to eq(
"\e[0;34mPry\e[0m"
)
end

it "with bold" do
expect(
colorize("Pry", bold: true)
).to eq(
"\e[1mPry\e[0m"
)
end

it "with color and bold" do
expect(
colorize("Pry", :blue, bold: true)
).to eq(
"\e[1;34mPry\e[0m"
)
end

it "with color, faded, and bold" do
expect(
colorize("Pry", :blue, bold: true, faded: true)
).to eq(
"\e[1;2;34mPry\e[0m"
)
end

it "unchanged" do
expect(
colorize("Pry", nil)
).to eq(
"\e[0mPry\e[0m"
)
end
end
end

0 comments on commit bf81539

Please sign in to comment.