Skip to content

Commit

Permalink
add headers_only options to csv_builder to only generate headers
Browse files Browse the repository at this point in the history
  • Loading branch information
dzfolio committed Jun 8, 2024
1 parent cb19716 commit 45be16b
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
6 changes: 5 additions & 1 deletion lib/as_csv/csv_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ def headers
end

def data_rows
@data_rows ||= csv_hashes.collect { |csv_hash| data_row csv_hash }
@data_rows ||= if options[:headers_only]
[]
else
csv_hashes.collect { |csv_hash| data_row csv_hash }
end
end

def validate
Expand Down
26 changes: 25 additions & 1 deletion spec/lib/csv_builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@
it 'should render correctly' do
should eq "first,second,third\n1,2,3\n"
end

context 'with headers_only option' do
let(:options) { { headers_only: true } }

it 'should render only headers' do
should eq "first,second,third\n"
end
end
end

context 'with homogenous records' do
Expand All @@ -37,9 +45,17 @@
it 'should render correctly' do
should == "first,second,third\n10,20,30\n11,21,31\n"
end

context 'with headers_only option' do
let(:options) { { headers_only: true } }

it 'should render only headers' do
should eq "first,second,third\n"
end
end
end

context 'with hetreogenous records' do
context 'with heterogeneous records' do
let(:records) do
2.times.map do |i|
double(:foo, :as_csv => {
Expand All @@ -56,6 +72,14 @@
,,,11,21,31
"
end

context 'with headers_only option' do
let(:options) { { headers_only: true } }

it 'should render only headers' do
should eq "first0,second0,third0,first1,second1,third1\n"
end
end
end

context 'with record not respond_to? `as_csv`' do
Expand Down

0 comments on commit 45be16b

Please sign in to comment.