You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.2 KiB
70 lines
1.2 KiB
2 years ago
|
require "csv"
|
||
|
|
||
2 years ago
|
class BulkUpload::Lettings::Year2022::CsvParser
|
||
|
MAX_COLUMNS = 136
|
||
|
|
||
2 years ago
|
attr_reader :path
|
||
|
|
||
|
def initialize(path:)
|
||
|
@path = path
|
||
|
end
|
||
|
|
||
|
def row_offset
|
||
2 years ago
|
with_headers? ? 5 : 0
|
||
2 years ago
|
end
|
||
|
|
||
|
def col_offset
|
||
2 years ago
|
with_headers? ? 1 : 0
|
||
2 years ago
|
end
|
||
|
|
||
|
def cols
|
||
|
@cols ||= ("A".."EE").to_a
|
||
|
end
|
||
|
|
||
|
def row_parsers
|
||
|
@row_parsers ||= body_rows.map do |row|
|
||
2 years ago
|
stripped_row = row[col_offset..]
|
||
2 years ago
|
headers = ("field_1".."field_134").to_a
|
||
|
hash = Hash[headers.zip(stripped_row)]
|
||
|
|
||
2 years ago
|
BulkUpload::Lettings::Year2022::RowParser.new(hash)
|
||
2 years ago
|
end
|
||
|
end
|
||
|
|
||
|
def body_rows
|
||
|
rows[row_offset..]
|
||
|
end
|
||
|
|
||
|
def rows
|
||
|
@rows ||= CSV.parse(normalised_string, row_sep:)
|
||
|
end
|
||
|
|
||
2 years ago
|
def column_for_field(field)
|
||
|
cols[headers.find_index(field) + col_offset]
|
||
|
end
|
||
|
|
||
2 years ago
|
private
|
||
|
|
||
2 years ago
|
def headers
|
||
|
@headers ||= ("field_1".."field_134").to_a
|
||
|
end
|
||
|
|
||
2 years ago
|
def with_headers?
|
||
|
rows[0][0]&.match?(/\D+/)
|
||
|
end
|
||
|
|
||
2 years ago
|
def row_sep
|
||
|
"\n"
|
||
|
end
|
||
|
|
||
|
def normalised_string
|
||
|
return @normalised_string if @normalised_string
|
||
|
|
||
2 years ago
|
@normalised_string = File.read(path, encoding: "bom|utf-8")
|
||
2 years ago
|
@normalised_string.gsub!("\r\n", "\n")
|
||
2 years ago
|
@normalised_string.scrub!("")
|
||
2 years ago
|
|
||
|
@normalised_string
|
||
|
end
|
||
|
end
|