diff --git a/Gemfile.lock b/Gemfile.lock index f7d9ad4..27256a7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - enumbler (0.4.0) + enumbler (0.4.1) activerecord (~> 6.0.2) activesupport (~> 6.0.2) diff --git a/lib/enumbler/enabler.rb b/lib/enumbler/enabler.rb index dd7fcbe..4dc79bf 100644 --- a/lib/enumbler/enabler.rb +++ b/lib/enumbler/enabler.rb @@ -144,18 +144,27 @@ def ids_from_enumbler(*args) end end - # Seeds the database with the Enumble data. + # Seeds the database with the Enumbler data. # @param delete_missing_records [Boolean] remove any records that are no # longer defined (default: false) def seed_the_enumbler(delete_missing_records: false) max_database_id = all.order('id desc').take&.id || 0 max_enumble_id = enumbles.map(&:id).max - max_id = max_enumble_id > max_database_id ? max_enumble_id : max_database_id + # If we are not deleting records, we just need to update each listed + # enumble and skip anything else in the database. If we are deleting + # records, we need to know the max database id. + iterator = if !delete_missing_records + @enumbles.map(&:id) + elsif max_enumble_id > max_database_id + (1..max_enumble_id) + else + (1..max_database_id) + end discarded_ids = [] - (1..max_id).each do |id| + iterator.each do |id| enumble = @enumbles.find { |e| e.id == id } if enumble.nil? diff --git a/lib/enumbler/version.rb b/lib/enumbler/version.rb index f8ca6e8..f022ce5 100644 --- a/lib/enumbler/version.rb +++ b/lib/enumbler/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Enumbler - VERSION = '0.4.0' + VERSION = '0.4.1' end diff --git a/spec/enumbler_spec.rb b/spec/enumbler_spec.rb index bcc7663..8437099 100644 --- a/spec/enumbler_spec.rb +++ b/spec/enumbler_spec.rb @@ -177,7 +177,7 @@ class House < ApplicationRecord end end - describe '.seed_the_enumbler', :seed do + describe '.seed_the_enumbler!', :seed do it 'uses a custom label' do expect(Color.infinity.label).to eq 'This is a made-up color' end @@ -192,4 +192,19 @@ class House < ApplicationRecord Color.enumbles.pop end end + + describe '.seed_the_enumbler', :seed do + context 'when delete_missing_records is false' do + it 'updates but does not delete the records' do + Color.enumble :pink, 8 + + kept = Color.create!(id: 5, label: 'this is to be kept but not enumbled') + Color.seed_the_enumbler(delete_missing_records: false) + + expect(Color.pink).to eq Color.find(8) + expect(Color.find_by(id: 5)).to eq kept + Color.enumbles.pop + end + end + end end