Skip to content

Instantly share code, notes, and snippets.

@dv
Last active August 29, 2015 14:05
Show Gist options
  • Save dv/f447c9601d5d98957855 to your computer and use it in GitHub Desktop.
Save dv/f447c9601d5d98957855 to your computer and use it in GitHub Desktop.
# services/csv_importer.rb
class CSVImporter
attr_reader :failed_rows, :success_count
def initialize(content, separator, paid_column)
@content = content
@separator = separator
@paid_column = paid_column
@failed_rows = []
@success_count = 0
end
def call
CSV.parse(@content, col_sep: @separator, headers: :first_row) do |row|
if parse_row(row)
@success_count += 1
else
@failed_rows << row
end
end
end
private
def parse_row(row)
registration = Registration.find_payment_code_from_csv(row.to_s)
if registration.blank?
return false
end
amount = amount_from_row(row)
if amount.nil?
return false
end
update_registration(registration, amount)
if registration.is_paid
RegistrationMailer.ticket(registration).deliver
else
RegistrationMailer.confirm_registration(registration).deliver
end
registration
end
def amount_from_row(row)
Float(row[@paid_column].sub(',', '.'))
rescue
nil
end
def update_registration(registration, amount)
registration.paid += amount
registration.payment_code = Registration.create_payment_code
registration.save!
end
end
class RegistrationsController < ApplicationController
# ...
def upload
@event = Event.find(params[:event_id])
authorize! :update, @event
separator = params[:separator]
csv_content = params[:csv_file].read.upcase
paid_column = params[:amount_column].upcase
importer = CSVImporter.new(csv_content, separator, paid_column)
importer.call
success_msg = "Updated #{'payment'.pluralize(importer.success_count)} successfully."
if importer.failed_rows.any?
flash.now[:success] = success_msg
flash.now[:error] = "The rows listed below contained an invalid code, please fix them by hand."
@csvheaders = importer.failed_rows.first.headers
@csvfails = importer.failed_rows
render 'upload'
else
redirect_to action: :index, success: success_msg
end
rescue CSV::MalformedCSVError
redirect_to action: :index, error: "The file could not be parsed. Make sure that you uploaded the correct file and that the column seperator settings have been set to the correct seperator."
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment