Last active
November 9, 2018 22:08
-
-
Save dudo/55f0cc6833818a08b01e306ea5a9f4a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class CsvSerializer | |
attr_accessor :data | |
def initialize(serializer) | |
@serializer = serializer | |
@data = serializer&.serializable_hash&.dig(:data) || [] | |
end | |
def as_csv | |
CSV.generate(headers: true, col_sep: "\t") do |csv| | |
csv << headers.map { |h| h.to_s.titleize } | |
data.each { |hash| csv << row(hash[:attributes]) } | |
end | |
end | |
private | |
def headers | |
return ['No data'] if data.blank? | |
@headers ||= @serializer.class.attributes_to_serialize.to_h.keys | |
end | |
def row(attributes) | |
attributes.each_with_object([]) { |(k, v), o| o[headers.index(k)] = v } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment