puzzle-scoreboard/app/models/csv_import.rb
sto 939e2157ab
All checks were successful
CI / scan_ruby (push) Successful in 20s
CI / scan_js (push) Successful in 12s
CI / lint (push) Successful in 12s
CI / test (push) Successful in 32s
Start CSV importer feature
2025-05-17 12:03:10 +02:00

47 lines
1.2 KiB
Ruby

# == Schema Information
#
# Table name: csv_imports
#
# id :integer not null, primary key
# separator :integer not null
# created_at :datetime not null
# updated_at :datetime not null
#
class CsvImport < ApplicationRecord
enum :separator, { comma: ",", semicolon: ";" }, default: :comma
has_one_attached :file
validates :file, presence: true
validate :acceptable_csv, on: :create
def acceptable_csv
return unless file.attached?
if file.blob.byte_size > 20
errors.add(:file, "this csv file is too large, it must be under 20MB")
return
end
if file.content_type != "text/csv"
errors.add(:file, :not_a_csv_file)
return
end
begin
csv = CSV.read(attachment_changes["file"].attachable.path, col_sep: separator)
logger = Logger.new(STDOUT)
logger.info(csv)
errors.add(:file, :empty) if csv.count < 1 || (csv.count == 1 && csv[0].count == 1 && csv[0][0] == "")
rescue CSV::MalformedCSVError => e
errors.add(:file, e.message)
end
end
def options_for_separator
keys = self.class.separators.keys
keys.map(&:humanize).zip(keys).to_h
end
end