Class: Karafka::Helpers::ClassMatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/karafka/helpers/class_matcher.rb

Overview

Class used to autodetect corresponding classes that are internally inside Karafka framework It is used among others to match:

consumer => responder

Constant Summary collapse

CONSTANT_REGEXP =

Regexp used to remove any non classy like characters that might be in the consumer class name (if defined dynamically, etc)

%r{[?!=+\-\*/\^\|&\[\]<>%~\#\:\s\(\)]}

Instance Method Summary collapse

Constructor Details

#initialize(klass, from:, to:) ⇒ ClassMatcher

Returns a new instance of ClassMatcher.

Examples:

Consumer that has a corresponding responder

matcher = Karafka::Helpers::ClassMatcher.new(SuperConsumer, 'Consumer', 'Responder')
matcher.match #=> SuperResponder

Consumer without a corresponding responder

matcher = Karafka::Helpers::ClassMatcher.new(Super2Consumer, 'Consumer', 'Responder')
matcher.match #=> nil

Parameters:

  • klass (Class)

    class to which we want to find a corresponding class

  • from (String)

    what type of object is it (based on postfix name part)

  • to (String)

    what are we looking for (based on a postfix name part)



22
23
24
25
26
# File 'lib/karafka/helpers/class_matcher.rb', line 22

def initialize(klass, from:, to:)
  @klass = klass
  @from = from
  @to = to
end

Instance Method Details

#matchClass?

Returns:

  • (Class)

    matched class

  • (nil)

    nil if we couldn’t find matching class



30
31
32
33
34
35
# File 'lib/karafka/helpers/class_matcher.rb', line 30

def match
  return nil if name.empty?
  return nil unless scope.const_defined?(name)
  matching = scope.const_get(name)
  same_scope?(matching) ? matching : nil
end

#nameString

Note:

This method returns name of a class without a namespace

Returns name of a new class that we’re looking for.

Examples:

From SuperConsumer matching responder

matcher.name #=> 'SuperResponder'

From Namespaced::Super2Consumer matching responder

matcher.name #=> Super2Responder

Returns:

  • (String)

    name of a new class that we’re looking for



43
44
45
46
47
48
# File 'lib/karafka/helpers/class_matcher.rb', line 43

def name
  inflected = @klass.to_s.split('::').last.to_s
  inflected.gsub!(@from, @to)
  inflected.gsub!(CONSTANT_REGEXP, '')
  inflected
end

#scopeClass, Module

Returns class or module in which we’re looking for a matching.

Returns:

  • (Class, Module)

    class or module in which we’re looking for a matching



51
52
53
# File 'lib/karafka/helpers/class_matcher.rb', line 51

def scope
  scope_of(@klass)
end