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 = { ...@@ -20,4 +20,4 @@ columns = {
'Labels' => -> (issue) { labels[issue.id].sort.join(',').presence } '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. # Generates CSV when given a collection and a mapping.
#
# 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.
# #
# Example: # Example:
# #
...@@ -15,18 +9,27 @@ ...@@ -15,18 +9,27 @@
# 'Created At (UTC)' => -> (post) { post.created_at&.strftime('%Y-%m-%d %H:%M:%S') } # '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 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 @header_to_value_hash = header_to_value_hash
@collection = collection
end end
def render(collection) # Renders the csv to a string
def render
CSV.generate do |csv| CSV.generate do |csv|
csv << headers csv << headers
collection.each do |object| @collection.each do |object|
csv << row(object) csv << row(object)
end end
end end
......
...@@ -2,8 +2,8 @@ require 'spec_helper' ...@@ -2,8 +2,8 @@ require 'spec_helper'
describe CsvBuilder, lib: true do describe CsvBuilder, lib: true do
let(:object) { double(question: :answer) } let(:object) { double(question: :answer) }
let(:subject) { CsvBuilder.new('Q & A' => :question, 'Reversed' => -> (o) { o.question.to_s.reverse }) } let(:subject) { CsvBuilder.new([object], 'Q & A' => :question, 'Reversed' => -> (o) { o.question.to_s.reverse }) }
let(:csv_data) { subject.render([object]) } let(:csv_data) { subject.render }
it 'generates a csv' do it 'generates a csv' do
expect(csv_data.scan(/(,|\n)/).join).to include ",\n," 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