From a7703c5b1ef64ebefb6f4a85acfdf90b1af1b9ab Mon Sep 17 00:00:00 2001 From: Mikhail Nelaev Date: Fri, 1 Jun 2018 17:27:45 +0500 Subject: [PATCH] feature: removing nonprintable characters https://jira.railsc.ru/browse/GOODS-1126 --- lib/string_tools/core_ext/string.rb | 24 ++++++++++++++++++++++++ spec/string_spec.rb | 12 ++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lib/string_tools/core_ext/string.rb b/lib/string_tools/core_ext/string.rb index bbef1a9..6d03eb6 100644 --- a/lib/string_tools/core_ext/string.rb +++ b/lib/string_tools/core_ext/string.rb @@ -204,6 +204,30 @@ def mb_downcase mb_chars.downcase.to_s end + # Public: returns copy of string with all non-printable characters removed + # + # Examples + # + # "q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable + # # => "qwerty" + # + # Returns String + def remove_nonprintable + gsub(/[^[:print:]]/i, '') + end + + # Public: removes all non-printable characters from string + # + # Examples + # + # "q\uFFFEw\uFFFFe\uFFF0r\uFDD0t\uFDEFy".remove_nonprintable! + # # => "qwerty" + # + # Returns String + def remove_nonprintable! + replace(remove_nonprintable) + end + private def surround_with_ansi(ascii_seq) diff --git a/spec/string_spec.rb b/spec/string_spec.rb index 23d584d..11f9e26 100644 --- a/spec/string_spec.rb +++ b/spec/string_spec.rb @@ -6,4 +6,16 @@ describe '#mb_downcase' do it { expect("Кириллица".mb_downcase).to eq("кириллица") } end + + describe '#remove_nonprintable' do + let(:string) { "\uFDD1string\uFFFE \uFFFFwith\uFDEF weird characters\uFDD0" } + + it { expect(string.remove_nonprintable).to eq 'string with weird characters' } + end + + describe '#remove_nonprintable!' do + let(:string) { "\uFDD1string\uFFFE \uFFFFwith\uFDEF weird characters\uFDD0" } + + it { expect { string.remove_nonprintable! }.to change { string }.to('string with weird characters') } + end end