Skip to content

Commit

Permalink
Add uncolor method
Browse files Browse the repository at this point in the history
  • Loading branch information
ypresto committed Jul 4, 2017
1 parent 1a61b33 commit 48fbee5
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
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

0 comments on commit 48fbee5

Please sign in to comment.