Skip to content

Commit

Permalink
update: simplified code
Browse files Browse the repository at this point in the history
  • Loading branch information
seenanair committed Jan 13, 2025
1 parent cfe528f commit a02be99
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 18 deletions.
21 changes: 5 additions & 16 deletions lib/singular_resource_versioned_tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'.
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions spec/support/it_behaves_like_a_singular_resource_versioned.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down

0 comments on commit a02be99

Please sign in to comment.