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

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)



24
25
26
27
28
# File 'lib/karafka/helpers/class_matcher.rb', line 24

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



32
33
34
35
36
37
38
# File 'lib/karafka/helpers/class_matcher.rb', line 32

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



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/karafka/helpers/class_matcher.rb', line 46

def name
  inflected = +@klass.to_s.split('::').last.to_s
  # We inject the from into the name just in case it is missing as in a situation like
  # that it would just sanitize the name without adding the "to" postfix.
  # It could create cases when we want to build for example a responder to a consumer
  # that does not have the "Consumer" postfix and would do nothing returning the same name.
  # That would be bad as the matching classes shouldn't be matched to themselves.
  inflected << @from unless inflected.include?(@from)
  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



60
61
62
# File 'lib/karafka/helpers/class_matcher.rb', line 60

def scope
  scope_of(@klass)
end