Class: BBK::App::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/bbk/app/handler.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Handler

Returns a new instance of Handler.



5
6
7
8
9
10
11
12
13
14
# File 'lib/bbk/app/handler.rb', line 5

def initialize(&block)
  @handlers = {}
  @default = if block_given?
    block
  else
    lambda do |*_args|
      # delivery_info, properties, body = message
    end
  end
end

Instance Method Details

#default(&block) ⇒ Object



53
54
55
# File 'lib/bbk/app/handler.rb', line 53

def default(&block)
  @default = block
end

#match(metadata, payload, delivery_info) ⇒ Object



57
58
59
60
61
62
63
64
# File 'lib/bbk/app/handler.rb', line 57

def match(, payload, delivery_info)
  @handlers.each_with_object([nil, @default]) do |p, _res|
    m, h = p
    if (match = m.match(, payload, delivery_info))
      return [match, h]
    end
  end
end

#register(*args, **kwargs, &block) ⇒ Object

регистрация обработчика тип матчера, парметры матчера, Обработчик | Класс обработчика, [аргументы обработчика]



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/bbk/app/handler.rb', line 18

def register(*args, **kwargs, &block)
  type, rule, callable = nil

  if args.first.respond_to?(:rule)
    type, *rule = args.first.rule
  elsif args.first.is_a?(Symbol) || args.first.is_a?(String)
    type = args.shift.to_sym
    rule = args.shift
    if rule.nil?
      $logger&.warn("Not found processor rule in positional arguments. Use keyword arguments #{kwargs} as rule")
      rule = kwargs
      kwargs = {}
    end
    raise "rule is not a Hash: #{args.inspect}" unless rule.is_a?(Hash)
  else
    raise "type and rule or method :rule missing: #{args.inspect}"
  end
  args.push block if block_given?

  callable = if args.first.is_a?(Class)
    BBK::App::Factory.new(*args, **kwargs)
  elsif args.first.respond_to?(:call)
    args.first
  else
    raise "callable object or class missing: #{args.inspect}"
  end

  matcher = BBK::App::Matchers.create(type, *[rule].flatten)
  @handlers.each do |m, _c|
    $logger&.warn("Handler with same matcher already registered: #{m.inspect}") if m == matcher
  end

  @handlers[BBK::App::Matchers.create(type, *[rule].flatten)] = callable
end