Class: Nuntius::ImportSubscribersJob
- Inherits:
-
ApplicationJob
- Object
- ActiveJob::Base
- ApplicationJob
- Nuntius::ImportSubscribersJob
- Defined in:
- app/jobs/nuntius/import_subscribers_job.rb
Constant Summary collapse
- KNOWN_COLUMNS =
%i[id first_name last_name email phone_number tags].freeze
Instance Method Summary collapse
-
#detect_column_separator(io) ⇒ Object
Detect column separator based on the first 50 bytes of the CSV, it’s naive but works for most cases.
- #import(list, io, user) ⇒ Object
- #perform(list, blob, user) ⇒ Object
Instance Method Details
#detect_column_separator(io) ⇒ Object
Detect column separator based on the first 50 bytes of the CSV, it’s naive but works for most cases
49 50 51 52 |
# File 'app/jobs/nuntius/import_subscribers_job.rb', line 49 def detect_column_separator(io) @column_separator = io.read(128).include?(";") ? ";" : "," io.rewind end |
#import(list, io, user) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'app/jobs/nuntius/import_subscribers_job.rb', line 17 def import(list, io, user) imported = 0 failed = 0 detect_column_separator(io) CSV.parse(io, headers: true, header_converters: :symbol, converters: ->(v) { v&.strip }, col_sep: @column_separator) do |row| row_hash = row.to_h attrs = row_hash.slice(*KNOWN_COLUMNS) extra = row_hash.except(*KNOWN_COLUMNS).reject { |_, v| v.nil? } attrs[:metadata] = extra unless extra.empty? subscriber = if attrs[:id].present? s = list.subscribers.find_by(id: attrs[:id]) s.assign_attributes(attrs) s else list.subscribers.new(attrs) end if subscriber.save imported += 1 else failed += 1 end end Signum.success(user, text: I18n.t("nuntius.admin.lists.subscribers.import.success", imported: imported, failed: failed)) if defined?(Signum) rescue CSV::MalformedCSVError => e Signum.error(user, text: I18n.t("nuntius.admin.lists.subscribers.import.invalid_csv", message: e.)) if defined?(Signum) end |
#perform(list, blob, user) ⇒ Object
9 10 11 12 13 14 15 |
# File 'app/jobs/nuntius/import_subscribers_job.rb', line 9 def perform(list, blob, user) blob.open do |io| import(list, io, user) end ensure blob.purge end |