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 uncolor method #54

Merged
merged 1 commit into from
Aug 15, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/rainbow/global.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ def self.enabled
def self.enabled=(value)
global.enabled = value
end

def self.uncolor(string)
StringUtils.uncolor(string)
end
end

def Rainbow(string)
Expand Down
5 changes: 5 additions & 0 deletions lib/rainbow/string_utils.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,10 @@ def self.wrap_with_sgr(string, codes)

string
end

def self.uncolor(string)
# See http://www.commandlinefu.com/commands/view/3584/remove-color-codes-special-characters-with-sed
string.gsub(/\e\[[0-9;]*m/, '')
end
end
end
14 changes: 14 additions & 0 deletions spec/integration/uncolor_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require 'spec_helper'
require 'rainbow'

describe 'uncolor method' do

it 'strips ansi color escape code' do
expect(Rainbow.uncolor("\e[35mhello\e[0mm")).to eq 'hellom'
end

it 'does not strip scroll down escape code' do
expect(Rainbow.uncolor("\e[1Thello")).to eq "\e[1Thello"
end

end
34 changes: 34 additions & 0 deletions spec/unit/string_utils_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,39 @@ class Stringgg < ::String; end
end
end
end

describe '.uncolor' do
subject { described_class.uncolor(string) }

context "when string with ansi color escape is passed" do
let(:string) do
rainbow = Rainbow.new
rainbow.enabled = true
rainbow.wrap('hello').
foreground(:red).
bright.
bold.
italic.
background('#ff8040').
underline.
color(:blue).
blink.
inverse.
hide
end

it "removes ansi color codes" do
expect(subject).to eq 'hello'
end
end

context "when string with scroll down ansi escape is passed" do
let(:string) { "\e[1Thello" }

it "does not remove ansi scroll down escape" do
expect(subject).to eq "\e[1Thello"
end
end
end
end
end