# frozen_string_literal: true module MrCommon # Imports PreRegistration records from a CSV file that looks like: # # first_name, last_name, email # John, Smith, jsmith@example.com # Jane, Doe, jdoe@example.com # ,,unknown@example.com # Name,Only, # # @author Corey Smedstad class PreRegistrationImporter RowStruct = Struct.new(:first_name, :last_name, :email) do # Returns true if the row does not represent a duplicate PreRegistration # @return [Boolean] def new? !PreRegistration.exists_for?(self) end end ResultStruct = Struct.new(:created, :skipped) attr_reader :csv, :current_row, :result # @param csv [String] a the contents of a CSV file def initialize(csv) @csv = csv @created = 0 @skipped = 0 end # Attempts to create PreRegistration records for each row in the CSV # recording the number of created and skipped records in the process. # # The result is memoized to prevent double imports. # # @returns [ResultStruct] the result of the import def import @result ||= perform_import end private def perform_import PreRegistration.transaction do rows.each do |data| load_row(data) if current_row.new? make_pre_registration else skip_pre_registration end end end ResultStruct.new(@created, @skipped) end def rows CSV.parse(csv, headers: true) end def load_row(data) first_name = data[0] || "" last_name = data[1] || "" email = data[2] || "" @current_row = RowStruct.new(first_name, last_name, email) end def make_pre_registration pre_registration = PreRegistration.new( first_name: current_row.first_name, last_name: current_row.last_name, email: current_row.email ) if pre_registration.save @created += 1 else skip_pre_registration end end def skip_pre_registration @skipped += 1 end end end