Commit 1a56196b authored by James Edwards-Jones's avatar James Edwards-Jones

Extracted CSV generation logic into CsvBuilder

parent f79b51ec
......@@ -13,18 +13,4 @@ columns = {
'Labels' => -> (issue) { issue.label_names.join(',').presence },
}
CSV.generate do |csv|
csv << columns.keys
@issues.each do |issue|
row = columns.values.map do |attribute|
if attribute.respond_to?(:call)
attribute.call(issue)
else
issue.send(attribute)
end
end
csv << row
end
end
CsvBuilder.new(columns).render(@issues)
class CsvBuilder
def initialize(header_to_value_hash)
@header_to_value_hash = header_to_value_hash
end
def render(collection)
CSV.generate do |csv|
csv << headers
collection.each do |object|
csv << row(object)
end
end
end
private
def headers
@header_to_value_hash.keys
end
def attributes
@header_to_value_hash.values
end
def row(object)
attributes.map do |attribute|
if attribute.respond_to?(:call)
attribute.call(object)
else
object.send(attribute)
end
end
end
end
require 'spec_helper'
describe CsvBuilder, lib: true do
let(:object) { double(question: :answer) }
let(:subject) { CsvBuilder.new('Q & A' => :question, 'Reversed' => -> (o) { o.question.to_s.reverse }) }
let(:csv_data) { subject.render([object]) }
it 'generates a csv' do
expect(csv_data.scan(/(,|\n)/).join).to include ",\n,"
end
it 'uses hash keys as headers' do
expect(csv_data).to start_with 'Q & A'
end
it 'gets data by calling method provided as hash value' do
expect(csv_data).to include 'answer'
end
it 'allows lamdas to look up more complicated data' do
expect(csv_data).to include 'rewsna'
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment