class CSVModel::Model
Attributes
data[R]
header[R]
keys[R]
parse_error[R]
rows[R]
Public Class Methods
new(data, options = {})
click to toggle source
# File lib/csv_model/model.rb, line 9 def initialize(data, options = {}) @data = data @rows = [] @options = options @keys = Set.new end
Public Instance Methods
row_count()
click to toggle source
# File lib/csv_model/model.rb, line 16 def row_count rows.count end
structure_errors()
click to toggle source
# File lib/csv_model/model.rb, line 20 def structure_errors return [parse_error] if parse_error return header.errors if !header.valid? [] end
structure_valid?()
click to toggle source
# File lib/csv_model/model.rb, line 26 def structure_valid? parse_error.nil? && header.valid? end
Protected Instance Methods
create_header_row(row)
click to toggle source
# File lib/csv_model/model.rb, line 40 def create_header_row(row) header_class.new(row, options) end
create_row(row, index)
click to toggle source
# File lib/csv_model/model.rb, line 44 def create_row(row, index) row = row_class.new(header, row, index, options) row.mark_as_duplicate if is_duplicate_key?(row.key) row end
detect_duplicate_rows?()
click to toggle source
# File lib/csv_model/model.rb, line 50 def detect_duplicate_rows? option(:detect_duplicate_rows, true) end
header_class()
click to toggle source
# File lib/csv_model/model.rb, line 54 def header_class option(:header_class, HeaderRow) end
is_duplicate_key?(value)
click to toggle source
# File lib/csv_model/model.rb, line 58 def is_duplicate_key?(value) return false if !detect_duplicate_rows? || value.nil? || value == "" || (value.is_a?(Array) && value.all_values_blank?) !keys.add?(value) end
parse_data()
click to toggle source
# File lib/csv_model/model.rb, line 63 def parse_data return if @parsed @parsed = true begin CSV.parse(data, { col_sep: "\t" }).each_with_index do |row, index| if index == 0 @header = create_header_row(row) end if row.size != header.column_count raise ParseError.new("Each row should have exactly #{header.column_count} columns. Error on row #{index + 1}.") end # TODO: Should we keep this? # if index > (limit - 1) # raise ParseError.new("You can only import #{limit} records at a time. Please split your import into multiple parts.") # end if index > 0 @rows << create_row(row, index) end end rescue CSV::MalformedCSVError => e @parse_error = "The data could not be parsed. Please check for formatting errors: #{e.message}" rescue ParseError => e @parse_error = e.message rescue Exception => e @parse_error = "An unexpected error occurred. Please try again or contact support if the issue persists: #{e.message}" end end
row_class()
click to toggle source
# File lib/csv_model/model.rb, line 95 def row_class option(:row_class, Row) end