Skip to content

Commit

Permalink
add Messages.counts_by_status (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
bedrock-adam authored Mar 16, 2024
1 parent 94619ca commit 662d0f8
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 2 deletions.
1 change: 1 addition & 0 deletions db/migrate/create_outboxer_messages.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def up
t.timestamps
end

add_index :outboxer_messages, :status
add_index :outboxer_messages, %i[status created_at]
end

Expand Down
12 changes: 12 additions & 0 deletions lib/outboxer/messages.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ module Messages
class Error < Outboxer::Error; end;
class InvalidTransition < Error; end

def counts_by_status
status_counts = Models::Message::STATUSES.each_with_object({}) do |status, hash|
hash[status.to_s] = 0
end

Models::Message.group(:status).count.each do |status, count|
status_counts[status.to_s] = count
end

status_counts
end

def unpublished!(limit: 1, order: :asc)
ActiveRecord::Base.connection_pool.with_connection do
message_ids = ActiveRecord::Base.transaction do
Expand Down
3 changes: 1 addition & 2 deletions lib/outboxer/models/message.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,10 @@ class Message < ::ActiveRecord::Base
module Status
UNPUBLISHED = 'unpublished'
PUBLISHING = 'publishing'
PUBLISHED = 'published'
FAILED = 'failed'
end

STATUSES = [Status::UNPUBLISHED, Status::PUBLISHING, Status::PUBLISHED, Status::FAILED]
STATUSES = [Status::UNPUBLISHED, Status::PUBLISHING, Status::FAILED]

scope :unpublished, -> { where(status: Status::UNPUBLISHED) }
scope :publishing, -> { where(status: Status::PUBLISHING) }
Expand Down
29 changes: 29 additions & 0 deletions spec/lib/outboxer/messages/counts_by_status_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
require 'spec_helper'

module Outboxer
RSpec.describe Message do
describe '.counts_by_status' do
context 'when no messages exist' do
it 'returns 0 for all statuses' do
expected_counts = { 'unpublished' => 0, 'publishing' => 0, 'failed' => 0 }

expect(Outboxer::Messages.counts_by_status).to eq(expected_counts)
end
end

context 'when messages exist' do
before do
create_list(:outboxer_message, 2, :unpublished)
create_list(:outboxer_message, 3, :publishing)
create_list(:outboxer_message, 4, :failed)
end

it 'returns correct counts for each status' do
expected_counts = { 'unpublished' => 2, 'publishing' => 3, 'failed' => 4 }

expect(Messages.counts_by_status).to eq(expected_counts)
end
end
end
end
end

0 comments on commit 662d0f8

Please sign in to comment.