# Copyright (c) 2020 Jerome Arbez-Gindre # frozen_string_literal: true require('csv') require('defmastership/export/body_formatter') require('defmastership/export/header_formatter') module Defmastership # Module to host export classes module Export # Module to host CSV export classes module CSV # to export a CSV file class Formatter # @param doc [Document] the document to export # @param sep [String] the CSV separator def initialize(doc, sep) @doc = doc @sep = sep end # Export the document to a CSV file # # @param output_file [Strinf] filename for the export def export_to(output_file) column_list = build_column_list ::CSV.open(output_file, 'w:ISO-8859-1', col_sep: @sep) do |csv| csv << header(column_list) export_definitions_in(csv, column_list) end end private def export_definitions_in(csv, column_list) @doc.definitions.each { |definition| csv << body(definition, column_list) } end def header(column_list) header_formatter = HeaderFormatter.new(@doc) header_line = column_list.map { |part| header_formatter.public_send(part) } header_line.flatten end def body(definition, column_list) body_formatter = BodyFormatter.new(@doc, definition) body_line = column_list.map { |part| body_formatter.public_send(part) } body_line.flatten end def build_column_list [ [:wrong_explicit_checksum, @doc.wrong_explicit_checksum?], [:explicit_version, @doc.explicit_version?], [:labels, !@doc.labels.empty?], [:eref, !@doc.eref.empty?], [:iref, @doc.iref], [:attributes, !@doc.attributes.empty?] ].reduce([:fixed]) { |acc, elem| acc + (elem.fetch(1) ? [elem.first] : []) } end end end end end