Skip to content

Commit 0c74dc8

Browse files
committed
Add CsvReportService
1 parent 7e02085 commit 0c74dc8

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Reports::CsvReportService
2+
delegate :csv, to: :@csv_service
3+
4+
def initialize(records)
5+
record_type = detect_record_type(records)
6+
@csv_service = csv_service_class(record_type).new(records)
7+
end
8+
9+
private
10+
11+
class NilCsvService
12+
def initialize(_records); end
13+
14+
def csv
15+
""
16+
end
17+
end
18+
19+
def csv_service_class(record_type)
20+
return NilCsvService if record_type.nil?
21+
22+
"Reports::#{record_type.capitalize}CsvReportService".constantize
23+
end
24+
25+
def detect_record_type(records)
26+
return if records.blank?
27+
28+
type = records.first.fetch("type", "form")
29+
30+
if type == "form"
31+
:forms
32+
elsif type == "question_page"
33+
:questions
34+
else
35+
raise "type of records '#{type}' is not one of 'forms', 'question_page'" unless type
36+
end
37+
end
38+
end
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
require "rails_helper"
2+
3+
RSpec.describe Reports::CsvReportService do
4+
subject(:csv_report_service) do
5+
described_class.new(records)
6+
end
7+
8+
describe "#csv" do
9+
context "when records is an empty list" do
10+
let(:records) { [] }
11+
12+
it "returns an empty string" do
13+
expect(csv_report_service.csv).to eq ""
14+
end
15+
end
16+
17+
context "when records is a list of form documents" do
18+
let(:records) { JSON.parse(file_fixture("form_documents_response.json").read) }
19+
20+
it "returns a CSV of forms" do
21+
expect(csv_report_service.csv).to eq Reports::FormsCsvReportService.new(records).csv
22+
end
23+
end
24+
25+
context "when records is a list of question page documents" do
26+
let(:records) { Reports::FeatureReportService.new(form_documents).questions }
27+
let(:form_documents) { JSON.parse(file_fixture("form_documents_response.json").read) }
28+
29+
it "returns a CSV of questions" do
30+
expect(csv_report_service.csv).to eq Reports::QuestionsCsvReportService.new(records).csv
31+
end
32+
end
33+
end
34+
end

0 commit comments

Comments
 (0)