Skip to content

Better sidekiq publisher conventions #50

@bedrock-adam

Description

@bedrock-adam
module OutboxerIntegration
  module Message
    class PublishJob
      include Sidekiq::Job

      sidekiq_options queue: 'events', retry: false, backtrace: true

      def perform(args)
        messageable_type = args['messageable_type']
        regex = /\A([A-Za-z]+)::Models::([A-Za-z]+)::([A-Za-z]+)Event\z/

        if !messageable_type.match(regex)
          raise StandardError, "Unexpected class name format: #{messageable_type}"
        end

        namespace, model, event = messageable_type.match(regex).captures
        job_class_name = "#{namespace}::#{model}#{event}Job"
        job_class = job_class_name.constantize
        job_class.perform_async({ 'id' => args['messageable_id'] })
      end
    end
  end
end
require 'rails_helper'

module OutboxerIntegration
  module Message
    RSpec.describe PublishJob, type: :job do
      describe '#perform' do
        let(:args) { {'messageable_type' => messageable_type, 'messageable_id' => '123'} }

        context 'with valid messageable_type' do
          let(:messageable_type) { 'Accountify::Models::Invoice::DraftedEvent' }

          it 'enqueues Accountify::Invoice::DraftedJob with the correct parameters' do
            PublishJob.new.perform(args)
            
            expect(Accountify::Invoice::DraftedJob).to have_enqueued_job.with({
              'id' => '123'
            })

            expect(Accountify::Invoice::DraftedJob.jobs.size).to eq(1)
          end
        end

        context 'with invalid messageable_type' do
          let(:messageable_type) { 'Wrong::Format::Test' }

          it 'raises an error for unexpected class name format' do
            expect {
              PublishJob.new.perform(args)
            }.to raise_error(StandardError, "Unexpected class name format: #{messageable_type}")
          end
        end
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions