Class: NatsListenerCore::AbstractSubscriber

Inherits:
Object
  • Object
show all
Defined in:
lib/nats_listener_core/abstract_subscriber.rb

Overview

Abstract class for nats and nats-streaming subscriptions

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client: nil) ⇒ AbstractSubscriber

Returns a new instance of AbstractSubscriber.



23
24
25
26
27
28
29
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 23

def initialize(client: nil)
  klass = self.class
  @subject = klass.const_get('SUBJECT')
  @count = klass.const_get('COUNT')
  @client = client || klass.client
  @infinitive = true if @count.zero?
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



21
22
23
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 21

def client
  @client
end

#sidObject (readonly)

Returns the value of attribute sid.



21
22
23
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 21

def sid
  @sid
end

Class Method Details

.count(count = 0) ⇒ Object

count method is used to define count of publications that subscription listens to If 0 - it’s infinitive Otherwise it decrements after each publication



16
17
18
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 16

def count(count = 0)
  const_set('COUNT', count)
end

.subject(subj) ⇒ Object

subject method is used to define subject for subscription



8
9
10
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 8

def subject(subj)
  const_set('SUBJECT', subj)
end

Instance Method Details

#around_call(msg, reply, subject) ⇒ Object



43
44
45
46
47
48
49
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 43

def around_call(msg, reply, subject)
  client.log(action: :received, message: msg.to_s)
  return unless should_call?

  call(msg, reply, subject)
  @count -= 1 unless @infinitive
end

#call(_msg, _reply, _subject) ⇒ Object



59
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 59

def call(_msg, _reply, _subject); end

#destroyObject



55
56
57
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 55

def destroy
  client.unsubscribe(sid)
end

#should_call?Boolean

Returns:

  • (Boolean)


51
52
53
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 51

def should_call?
  @count.positive? || @infinitive
end

#subscribe(opts = {}) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/nats_listener_core/abstract_subscriber.rb', line 31

def subscribe(opts = {})
  # Create subscription and delete after its finished if not infinitive
  @sid = client.subscribe(@subject, opts) do |msg, reply, subject|
    begin
      around_call(msg, reply, subject)
      destroy unless should_call?
    rescue StandardError => exception
      client.on_rescue(exception)
    end
  end
end