Sha256: 9f128e265a70882ee6959f36922c0ee8b9b25beecbffaef13647fc76cab23863

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

require 'dry-equalizer'
module Messaging
  module Routing
    # Internal: Used by subscribers to match messages.
    class MessageMatcher
      include Dry::Equalizer(:pattern, :topic_pattern)

      attr_accessor :pattern
      attr_accessor :topic_pattern

      def initialize(pattern:, topic: nil)
        self.pattern = pattern
        self.topic_pattern = topic
      end

      # Internal: See routing.rb for examples on how it is used.

      # Med case statement
      def matches?(message)
        matches_topic?(message) && matches_pattern?(message)
      end

      def matches_pattern?(message)
        case pattern
        when Regexp
          pattern =~ message.message_type
        when Class, Module
          /^#{pattern}/ =~ message.message_type
        when Proc
          pattern.call(message)
        else
          false
        end
      end

      def matches_topic?(message)
        return true unless topic_pattern

        case message.topic.to_s
        when topic_pattern then true
        else
          false
        end
      end

      def call(message)
        matches?(message)
      end

      def all_matching_messages
        Messaging.defined_messages.select(&method(:matches?))
      end

      # Internal: Get all topics that the matcher would need to match a message.
      #
      # Used by the Kafka adapter to setup consumers.
      def topics
        (Array(topic_pattern) + all_matching_messages.map(&:topic)).uniq
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
messaging-3.4.1 lib/messaging/routing/message_matcher.rb