diff --git a/lib/rainbow/global.rb b/lib/rainbow/global.rb index 4bdc8aa..ea5c692 100644 --- a/lib/rainbow/global.rb +++ b/lib/rainbow/global.rb @@ -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) diff --git a/lib/rainbow/string_utils.rb b/lib/rainbow/string_utils.rb index b2c732a..ad3e02e 100644 --- a/lib/rainbow/string_utils.rb +++ b/lib/rainbow/string_utils.rb @@ -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 diff --git a/spec/integration/uncolor_spec.rb b/spec/integration/uncolor_spec.rb new file mode 100644 index 0000000..9b401b8 --- /dev/null +++ b/spec/integration/uncolor_spec.rb @@ -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 diff --git a/spec/unit/string_utils_spec.rb b/spec/unit/string_utils_spec.rb index 3144aff..3716ce0 100644 --- a/spec/unit/string_utils_spec.rb +++ b/spec/unit/string_utils_spec.rb @@ -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