Class: GeoLabels::Importer::CsvData
- Inherits:
-
Object
- Object
- GeoLabels::Importer::CsvData
- Defined in:
- lib/geo_labels/importer/csv_data.rb
Constant Summary collapse
- ROW_ATTRIBUTES =
%w[name description state street subsection city department country url latitude longitude]
Instance Attribute Summary collapse
-
#new_contacts ⇒ Object
readonly
Returns the value of attribute new_contacts.
Instance Method Summary collapse
Instance Attribute Details
#new_contacts ⇒ Object (readonly)
Returns the value of attribute new_contacts.
7 8 9 |
# File 'lib/geo_labels/importer/csv_data.rb', line 7 def new_contacts @new_contacts end |
Instance Method Details
#import(data) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/geo_labels/importer/csv_data.rb', line 10 def import(data) @new_contacts = [] counter = 2 # start counting from 1 and skip the header. Works with Apple -> Numbers application CSV.parse(data, headers: true).each do |row| name = row['name'] raise "Row #{counter} has no name" unless name.present? label_names = row['labels'].to_s.strip.split('|').map(&:strip).select(&:present?) raise "Row #{counter} (#{name}) has no labels" unless label_names.any? labels = label_names.map do |label_name| labels_h[label_name] or raise "Row #{counter} has a label: '#{label_name}' that is not yet in the system. Please add before using it in an import" end contact = Contact.new(row.to_h.slice(*ROW_ATTRIBUTES)) contact.labels = labels raise "Row #{counter} creates an invalid contact. Errors: #{contact.errors.full_messages.to_sentence}" unless contact.valid? new_contacts.push contact counter += 1 end Contact.delete_all ContactLabel.delete_all new_contacts.each do |contact| contact.save! end end |
#labels_h ⇒ Object
38 39 40 |
# File 'lib/geo_labels/importer/csv_data.rb', line 38 def labels_h @labels_h ||= Label.all.map{ |l| [l.name, l] }.to_h end |