Skip to content

Commit b04ff66

Browse files
committed
add headers_only options to csv_builder to only generate headers
1 parent cb19716 commit b04ff66

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

lib/as_csv/csv_builder.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@ def headers
2626
end
2727

2828
def data_rows
29-
@data_rows ||= csv_hashes.collect { |csv_hash| data_row csv_hash }
29+
@data_rows ||= if options[:headers_only]
30+
[]
31+
else
32+
csv_hashes.collect { |csv_hash| data_row csv_hash }
33+
end
3034
end
3135

3236
def validate

spec/lib/csv_builder_spec.rb

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,14 @@
2121
it 'should render correctly' do
2222
should eq "first,second,third\n1,2,3\n"
2323
end
24+
25+
context 'with headers_only option' do
26+
let(:options) { {headers_only: true} }
27+
28+
it 'should render only headers' do
29+
should eq "first,second,third\n"
30+
end
31+
end
2432
end
2533

2634
context 'with homogenous records' do
@@ -37,9 +45,17 @@
3745
it 'should render correctly' do
3846
should == "first,second,third\n10,20,30\n11,21,31\n"
3947
end
48+
49+
context 'with headers_only option' do
50+
let(:options) { {headers_only: true} }
51+
52+
it 'should render only headers' do
53+
should eq "first,second,third\n"
54+
end
55+
end
4056
end
4157

42-
context 'with hetreogenous records' do
58+
context 'with heterogeneous records' do
4359
let(:records) do
4460
2.times.map do |i|
4561
double(:foo, :as_csv => {
@@ -56,6 +72,14 @@
5672
,,,11,21,31
5773
"
5874
end
75+
76+
context 'with headers_only option' do
77+
let(:options) { {headers_only: true} }
78+
79+
it 'should render only headers' do
80+
should eq "first0,second0,third0,first1,second1,third1\n"
81+
end
82+
end
5983
end
6084

6185
context 'with record not respond_to? `as_csv`' do

0 commit comments

Comments
 (0)