Skip to content

Instantly share code, notes, and snippets.

@dudo
Last active November 9, 2018 22:08
Show Gist options
  • Save dudo/55f0cc6833818a08b01e306ea5a9f4a6 to your computer and use it in GitHub Desktop.
Save dudo/55f0cc6833818a08b01e306ea5a9f4a6 to your computer and use it in GitHub Desktop.
# 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