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:

controller => worker
controller => responder

Constant Summary collapse

CONSTANT_REGEXP =

Regexp used to remove any non classy like characters that might be in the controller 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:

Controller that has a corresponding worker

matcher = Karafka::Helpers::ClassMatcher.new(SuperController, 'Controller', 'Worker')
matcher.match #=> SuperWorker

Controller without a corresponding worker

matcher = Karafka::Helpers::ClassMatcher.new(Super2Controller, 'Controller', 'Worker')
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)



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

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



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

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 SuperController matching worker

matcher.name #=> 'SuperWorker'

From Namespaced::Super2Controller matching worker

matcher.name #=> Super2Worker

Returns:

  • (String)

    name of a new class that we’re looking for



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

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



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

def scope
  scope_of(@klass)
end