Sha256: 11cc9bcf8ae65e5f1955858d482df13181beac8b4c4587b08a8ac96644d0d227

Contents?: true

Size: 1.52 KB

Versions: 4

Compression:

Stored size: 1.52 KB

Contents

module CSVImporter

  # The CSV Header
  class Header
    include Virtus.model

    attribute :column_definitions, Array[ColumnDefinition]
    attribute :column_names, Array[String]

    def columns
      column_names.map do |column_name|
        # ensure column name escapes invisible characters
        column_name = column_name.gsub(/[^[:print:]]/, '')

        Column.new(
          name: column_name,
          definition: find_column_definition(column_name)
        )
      end
    end

    def column_name_for_model_attribute(attribute)
      if column = columns.find { |column| column.definition.attribute == attribute if column.definition }
        column.name
      end
    end

    def valid?
      missing_required_columns.empty?
    end

    # Returns Array[String]
    def required_columns
      column_definitions.select(&:required?).map(&:name)
    end

    # Returns Array[String]
    def extra_columns
      columns.reject(&:definition).map(&:name).map(&:to_s)
    end

    # Returns Array[String]
    def missing_required_columns
      (column_definitions.select(&:required?) - columns.map(&:definition)).map(&:name).map(&:to_s)
    end

    # Returns Array[String]
    def missing_columns
      (column_definitions - columns.map(&:definition)).map(&:name).map(&:to_s)
    end

    private

    def find_column_definition(name)
      column_definitions.find do |column_definition|
        column_definition.match?(name)
      end
    end

    def column_definition_names
      column_definitions.map(&:name).map(&:to_s)
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
cm-admin-1.5.22 vendor/bundle/ruby/3.3.0/gems/csv-importer-0.8.2/lib/csv_importer/header.rb
cm-admin-1.5.21 vendor/bundle/ruby/3.3.0/gems/csv-importer-0.8.2/lib/csv_importer/header.rb
cm-admin-1.5.20 vendor/bundle/ruby/3.3.0/gems/csv-importer-0.8.2/lib/csv_importer/header.rb
csv-importer-0.8.2 lib/csv_importer/header.rb