Sha256: fde91e406991fb6191e24b3f1a3fdbe5e31ce94db4a65d82d8b33e286115220c

Contents?: true

Size: 1.45 KB

Versions: 9

Compression:

Stored size: 1.45 KB

Contents

# Copyright (c) 2020 Jerome Arbez-Gindre
# frozen_string_literal: true

require('csv')
require('defmastership/csv_formatter_header')
require('defmastership/csv_formatter_body')

module DefMastership
  # to export a CSV file
  class CSVFormatter
    def initialize(doc, sep = ',')
      @doc = doc
      @sep = sep
    end

    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)
        @doc.definitions.each { |definition| csv << body(definition, column_list) }
      end
    end

    private

    def header(column_list)
      header_formatter = CSVFormatterHeader.new(@doc)
      header_line = column_list.map { |part| header_formatter.public_send(part) }
      header_line.reduce(:+)
    end

    def body(definition, column_list)
      body_formatter = CSVFormatterBody.new(@doc)
      body_line = column_list.map { |part| body_formatter.public_send(part, definition) }
      body_line.reduce(:+)
    end

    def build_column_list
      column_list = [:fixed]
      column_list += [:wrong_explicit_checksum] if @doc.wrong_explicit_checksum?
      column_list += [:explicit_version] if @doc.explicit_version?
      column_list += [:labels] unless @doc.labels.empty?
      column_list += [:eref] unless @doc.eref.empty?
      column_list += [:iref] if @doc.iref
      column_list += [:attributes] unless @doc.attributes.empty?
      column_list
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
defmastership-1.0.16 lib/defmastership/csv_formatter.rb
defmastership-1.0.15 lib/defmastership/csv_formatter.rb
defmastership-1.0.14 lib/defmastership/csv_formatter.rb
defmastership-1.0.13 lib/defmastership/csv_formatter.rb
defmastership-1.0.12 lib/defmastership/csv_formatter.rb
defmastership-1.0.11 lib/defmastership/csv_formatter.rb
defmastership-1.0.10 lib/defmastership/csv_formatter.rb
defmastership-1.0.9 lib/defmastership/csv_formatter.rb
defmastership-1.0.8 lib/defmastership/csv_formatter.rb