class Eco::Data::Locations::NodePlain module Parsing attr_writer :node_class def node_class @node_class ||= Eco::Data::Locations::NodePlain end # Subset of property names expected to be among the headers def basic_headers @expected_headers ||= %w[id name parent_id] end # Checks if the `basic_headers` to process as `NodePlain` are present. # @param [CSV::Table] # @return [Boolean] whether or not it's worthy trying to parse with `NodePlain`. def csv_matches_format?(csv) return false unless csv.is_a?(::CSV::Table) (basic_headers & csv.headers) == basic_headers end # It builds each NodePlain from the input csv. # @param `csv` [CSV::Table] with specific headers # @return [Array] def nodes_from_csv(csv) raise ArgumentError, "Expecting CSV::Table. Given: #{csv.class}" unless csv.is_a?(::CSV::Table) # Convert to Eco::CSV::Table for a fresh start csv = Eco::CSV.parse(csv.to_csv).nil_blank_cells.add_index_column(:row_num) headers = node_class::ALL_ATTRS.map(&:to_s) csv.each_with_object([]) do |row, out| row_num, *values = row.values_at(*headers) out << node_class.new(row_num, *values) end end end end