Skip to content

Commit

Permalink
refactors to have override_id passed as an option
Browse files Browse the repository at this point in the history
  • Loading branch information
simaob committed Nov 22, 2019
1 parent 4321ecc commit 0e0045b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 14 deletions.
13 changes: 12 additions & 1 deletion app/services/csv_import/base_importer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,12 @@ class BaseImporter
attr_reader :file, :import_results
attr_accessor :override_id

def initialize(file)
# @param file [File]
# @param options [Hash]
# @option override_id [Boolean] override automatic ids and make use of id in the import data
def initialize(file, options={})
@file = file
@override_id = options[:override_id] if options[:override_id]
end

def call
Expand All @@ -17,6 +21,7 @@ def call

ActiveRecord::Base.transaction(requires_new: true) do
import
reset_id_seq if override_id
raise ActiveRecord::Rollback if errors.any?
end

Expand Down Expand Up @@ -60,6 +65,12 @@ def csv_converters

private

def reset_id_seq
table_name = resource_klass.table_name
seq_name = "#{table_name}_id_seq"
ActiveRecord::Base.connection.execute("select setval('#{seq_name}', max(id)) from #{table_name};")
end

def reset_import_results
@import_results = {
new_records: 0,
Expand Down
16 changes: 3 additions & 13 deletions db/seeds.rb
Original file line number Diff line number Diff line change
Expand Up @@ -92,11 +92,7 @@
# import companies
TimedLogger.log('Import companies') do
file = File.open(Rails.root.join('db', 'seeds', 'tpi-companies.csv'), 'r')
importer = CSVImport::Companies.new(file)
importer.override_id = true
importer.call

ActiveRecord::Base.connection.execute("select setval('companies_id_seq',max(id)) from companies;")
importer = CSVImport::Companies.new(file, override_id: true).call
end

# import CP Benchmarks
Expand Down Expand Up @@ -126,19 +122,13 @@
# import Legislations
TimedLogger.log('Import Legislations') do
file = File.open(Rails.root.join('db', 'seeds', 'legislations.csv'), 'r')
importer = CSVImport::Legislations.new(file)
importer.override_id = true
importer.call
ActiveRecord::Base.connection.execute("select setval('legislations_id_seq',max(id)) from legislations;")
importer = CSVImport::Legislations.new(file, override_id: true).call
end

TimedLogger.log('Import Litigations') do
# import Litigations
file = File.open(Rails.root.join('db', 'seeds', 'litigations.csv'), 'r')
importer = CSVImport::Litigations.new(file)
importer.override_id = true
importer.call
ActiveRecord::Base.connection.execute("select setval('litigations_id_seq',max(id)) from litigations;")
importer = CSVImport::Litigations.new(file, override_id: true).call

# import Litigation Sides
file = File.open(Rails.root.join('db', 'seeds', 'litigation-sides.csv'), 'r')
Expand Down

0 comments on commit 0e0045b

Please sign in to comment.