From a02be9942a86b701aef2e8cbf4bffdec642a094c Mon Sep 17 00:00:00 2001 From: Seena Nair <55585488+seenanair@users.noreply.github.com> Date: Mon, 13 Jan 2025 16:42:05 +0000 Subject: [PATCH] update: simplified code --- lib/singular_resource_versioned_tools.rb | 21 +++++-------------- ...aves_like_a_singular_resource_versioned.rb | 4 ++-- 2 files changed, 7 insertions(+), 18 deletions(-) diff --git a/lib/singular_resource_versioned_tools.rb b/lib/singular_resource_versioned_tools.rb index 63161ee0..4d93f4f6 100644 --- a/lib/singular_resource_versioned_tools.rb +++ b/lib/singular_resource_versioned_tools.rb @@ -15,8 +15,8 @@ module SingularResourceVersionedTools # @param other [ActiveRecord::Base] The record to compare with. # @yield [ActiveRecord::Base] Yields the given record if it is the latest and has changed. # @return [ActiveRecord::Base] Returns the current record if the given record is not the latest or has not changed. - def latest(other) - attributes_changed?(other) && (other.last_updated > last_updated) ? yield(other) : self + def latest?(other) + attributes_changed?(other) && (other.last_updated > last_updated) end # Compares the attributes of the current record with the given record, excluding 'id', 'created_at', and 'updated_at'. @@ -39,23 +39,12 @@ module ClassMethods def create_or_update(attributes) new_record = new(attributes.to_hash) - # byebug existing_record = for_lims(attributes.id_lims).with_id(attributes[base_resource_key]).order(last_updated: :desc) .first - # byebug - if existing_record.nil? - # byebug - # No existing record found, save the new record - new_record.save! - else - existing_record.latest(new_record) do |record| - # byebug - record.update(attributes.to_hash) if record.present? - record ||= new_record - record.save! - end - end + return unless existing_record.nil? || existing_record.latest?(new_record) + + new_record.save! end private :create_or_update end diff --git a/spec/support/it_behaves_like_a_singular_resource_versioned.rb b/spec/support/it_behaves_like_a_singular_resource_versioned.rb index 92c3b371..cb4e3355 100644 --- a/spec/support/it_behaves_like_a_singular_resource_versioned.rb +++ b/spec/support/it_behaves_like_a_singular_resource_versioned.rb @@ -96,14 +96,14 @@ def current_records described_class.create_or_update_from_json(timestamped_json.merge('last_updated' => modified_at + 1.hour), example_lims) end - it 'creates a new record with the updated fields' do + it 'does not create a new record' do expect(current_records.count).to eq(1) expect(current_records.last['last_updated']).to eq(modified_at) end end context 'when ignored fields change' do - ResourceTools::IGNOREABLE_ATTRIBUTES.each do |attribute| + SingularResourceVersionedTools::EXCLUDED_ATTRIBUTES.each do |attribute| next if attribute.to_s == 'dont_use_id' # Protected by mass-assignment! let(:most_recent_time) { modified_at }