diff --git a/lib/csv-safe.rb b/lib/csv-safe.rb index 2a799a7..26db103 100644 --- a/lib/csv-safe.rb +++ b/lib/csv-safe.rb @@ -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 diff --git a/spec/csv_safe_spec.rb b/spec/csv_safe_spec.rb index fba9f47..68f427e 100644 --- a/spec/csv_safe_spec.rb +++ b/spec/csv_safe_spec.rb @@ -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) } @@ -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] } @@ -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 }