Skip to content

Commit

Permalink
Add support for Arrays in replacing invalid characters
Browse files Browse the repository at this point in the history
  • Loading branch information
wallin committed Sep 19, 2017
1 parent 5b2b448 commit 1176d91
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
6 changes: 4 additions & 2 deletions lib/castle/replace_invalid_characters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
module Castle
class ReplaceInvalidCharacters
def self.call(arg)
if arg.is_a?(String)
if arg.is_a?(::String)
arg.encode('UTF-8', invalid: :replace, undef: :replace)
elsif arg.is_a?(Hash)
elsif arg.is_a?(::Hash)
arg.each_with_object({}) do |(k, v), h|
h[k] = call(v)
end
elsif arg.is_a?(::Array)
arg.map(&method(:call))
else
arg
end
Expand Down
28 changes: 21 additions & 7 deletions spec/lib/castle/replace_invalid_characters_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,29 @@
it { is_expected.to eq input }
end

context 'when input is a hash with invalid UTF-8 characters' do
let(:input) { { user_id: "inv\xC4lid" } }
context 'with invalid UTF-8 characters' do
context 'when input is a hash' do
let(:input) { { user_id: "inv\xC4lid" } }

it { is_expected.to eq(user_id: 'inv�lid') }
end
it { is_expected.to eq(user_id: 'inv�lid') }
end

context 'when input is a nested hash' do
let(:input) { { user: { id: "inv\xC4lid" } } }

it { is_expected.to eq(user: { id: 'inv�lid' }) }
end

context 'when input is an array of hashes' do
let(:input) { [{ user: "inv\xC4lid" }] * 2 }

it { is_expected.to eq([{ user: 'inv�lid' }, { user: 'inv�lid' }]) }
end

context 'when input is a nested hash with invalid UTF-8 characters' do
let(:input) { { user: { id: "inv\xC4lid" } } }
context 'when input is an array' do
let(:input) { ["inv\xC4lid"] * 2 }

it { is_expected.to eq(user: { id: 'inv�lid' }) }
it { is_expected.to eq(['inv�lid', 'inv�lid']) }
end
end
end

0 comments on commit 1176d91

Please sign in to comment.