Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 5 additions & 8 deletions lib/csv-safe.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,10 @@ def sanitize_field(field)
end

def sanitize_row(row)
case row
when self.class::Row
then row.fields.map { |field| sanitize_field(field) }
when Hash
then @headers.map { |header| sanitize_field(row[header]) }
else
row.map { |field| sanitize_field(field) }
end
return row.fields.map { |field| sanitize_field(field) } if row.is_a?(self.class::Row)

return headers.map { |header| sanitize_field(row[header]) } if row.is_a?(Hash) && !headers.nil?

row.map { |field| sanitize_field(field) }
end
end
30 changes: 23 additions & 7 deletions spec/csv_safe_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,12 @@ def self.to_s
end

describe '#sanitize_row' do
before(:all) do
CSV_Instance = CSVSafe.new('')
end
subject { CSV_Instance.send(:sanitize_row, row) }

context 'when the row is a CSV::Row' do
before(:all) do
CSV_Instance = CSVSafe.new('')
end
subject { CSV_Instance.send(:sanitize_row, row) }

context "when the fields don't require sanitization" do
let(:fields) { %w[Jane 30] }
let(:row) { CSV::Row.new(%w[Name Age], fields) }
Expand All @@ -143,9 +143,11 @@ def self.to_s
end

context 'when the row is a Hash' do
before do
CSV_Instance.instance_variable_set(:@headers, %i[Name Age])
before(:all) do
CSV_Instance = CSVSafe.new('', headers: %i[Name Age])
end
subject { CSV_Instance.send(:sanitize_row, row) }

context "when the fields don't require sanitization" do
let(:row) { { Name: 'Jane', Age: '30' } }
let(:expected) { %w[Jane 30] }
Expand All @@ -158,9 +160,23 @@ def self.to_s

it { should eq expected }
end

it "does not crash" do
headers = %i[a b c]
payload = { b: :b, a: :a, c: :c }

output = CSVSafe.generate(headers: true) { |csv| csv << headers; csv << payload }.split "\n"

expect(output).to eq(["a,b,c", "a,b,c"])
end
end

context 'when the row is an array' do
before(:all) do
CSV_Instance = CSVSafe.new('')
end
subject { CSV_Instance.send(:sanitize_row, row) }

context "when the fields don't require sanitization" do
let(:row) { %w[Jane 30] }
it { should eq row }
Expand Down