Commit 431d4b77 authored by James Edwards-Jones's avatar James Edwards-Jones

CsvBuilder takes collection in initializer instead of render

parent 91ac5c7b
......@@ -20,4 +20,4 @@ columns = {
'Labels' => -> (issue) { labels[issue.id].sort.join(',').presence }
}
CsvBuilder.new(columns).render(@issues.includes(:author, :assignee))
CsvBuilder.new(@issues.includes(:author, :assignee), columns).render
# Generates CSV when given a mapping and a collection.
#
# Takes a hash of 'Column Heading' => 'value_method'.
#
# The value method will be called once for each object in the collection, to
# determine the value for that row. It can either be the name of a method on
# the object, or a lamda to call passing in the object.
# Generates CSV when given a collection and a mapping.
#
# Example:
#
......@@ -15,18 +9,27 @@
# 'Created At (UTC)' => -> (post) { post.created_at&.strftime('%Y-%m-%d %H:%M:%S') }
# }
#
# CsvBuilder.new(columns).render(@posts)
# CsvBuilder.new(@posts, columns).render
#
class CsvBuilder
def initialize(header_to_value_hash)
#
# * +collection+ - The data collection to be used
# * +header_to_hash_value+ - A hash of 'Column Heading' => 'value_method'.
#
# The value method will be called once for each object in the collection, to
# determine the value for that row. It can either be the name of a method on
# the object, or a lamda to call passing in the object.
def initialize(collection, header_to_value_hash)
@header_to_value_hash = header_to_value_hash
@collection = collection
end
def render(collection)
# Renders the csv to a string
def render
CSV.generate do |csv|
csv << headers
collection.each do |object|
@collection.each do |object|
csv << row(object)
end
end
......
......@@ -2,8 +2,8 @@ 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]) }
let(:subject) { CsvBuilder.new([object], 'Q & A' => :question, 'Reversed' => -> (o) { o.question.to_s.reverse }) }
let(:csv_data) { subject.render }
it 'generates a csv' do
expect(csv_data.scan(/(,|\n)/).join).to include ",\n,"
......
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