Skip to content

Commit

Permalink
Add strip_ansi_escape method
Browse files Browse the repository at this point in the history
  • Loading branch information
ypresto committed Jul 2, 2017
1 parent 1a61b33 commit 3ec8d82
Show file tree
Hide file tree
Showing 4 changed files with 43 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.strip_ansi_escape(string)
StringUtils.strip_ansi_escape(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.strip_ansi_escape(string)
# See http://www.commandlinefu.com/commands/view/3584/remove-color-codes-special-characters-with-sed
string.gsub(/\e\[[0-9;]*[a-zA-Z]/, '')
end
end
end
10 changes: 10 additions & 0 deletions spec/integration/strip_ansi_escape_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
require 'spec_helper'
require 'rainbow'

describe 'strip_ansi_escape method' do

it 'strips ansi escape codes' do
expect(Rainbow.strip_ansi_escape("\e[35mhello\e[0m")).to eq 'hello'
end

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

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

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
end
end

0 comments on commit 3ec8d82

Please sign in to comment.