Skip to content

Commit

Permalink
Reduce number of transactions for #mark_collection_as_read
Browse files Browse the repository at this point in the history
  • Loading branch information
fatkodima committed Jan 21, 2018
1 parent e3e9626 commit 747df0f
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 14 deletions.
17 changes: 6 additions & 11 deletions lib/unread/readable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,17 +27,12 @@ def mark_collection_as_read(collection, reader)
if global_timestamp && global_timestamp >= timestamp
# The object is implicitly marked as read, so there is nothing to do
else
# This transaction is needed, so that parent transaction won't rollback even there's an error.
ReadMark.transaction(requires_new: true) do
begin
rm = obj.read_marks.where(reader_id: reader.id, reader_type: reader.class.base_class.name).first || obj.read_marks.build
rm.reader_id = reader.id
rm.reader_type = reader.class.base_class.name
rm.timestamp = timestamp
rm.save!
rescue ActiveRecord::RecordNotUnique
raise ActiveRecord::Rollback
end
begin
rm = obj.read_marks.find_or_initialize_by(reader_id: reader.id, reader_type: reader.class.base_class.name)
rm.timestamp = timestamp
rm.save!
rescue ActiveRecord::RecordNotUnique
next
end
end
end
Expand Down
3 changes: 1 addition & 2 deletions spec/unread/readable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,7 @@
it "should mark the rest as read when the first record is not unique" do
Email.mark_as_read! [ @email1 ], for: @reader

allow(@email1).to receive_message_chain("read_marks.build").and_return(@email1.read_marks.build)
allow(@email1).to receive_message_chain("read_marks.where").and_return([])
allow(@email1).to receive("read_marks.find_or_initialize_by").and_return(@email1.read_marks.build)

expect do
Email.mark_as_read! [ @email1, @email2 ], for: @reader
Expand Down
2 changes: 1 addition & 1 deletion unread.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Gem::Specification.new do |s|
s.add_development_dependency 'timecop'
s.add_development_dependency 'sqlite3'
s.add_development_dependency 'mysql2'
s.add_development_dependency 'pg'
s.add_development_dependency 'pg', '< 1'
s.add_development_dependency 'rspec'
s.add_development_dependency 'simplecov'
s.add_development_dependency 'term-ansicolor'
Expand Down

0 comments on commit 747df0f

Please sign in to comment.