Class: Moleculer::Packets::Base Abstract

Inherits:
Object
  • Object
show all
Includes:
Support
Defined in:
lib/moleculer/packets/base.rb

Overview

This class is abstract.

Subclass for packet types.

Direct Known Subclasses

Disconnect, Discover, Event, Heartbeat, Info, Req, Res

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, data = {}) ⇒ Base

Returns a new instance of Base.

Parameters:

  • data (Hash) (defaults to: {})

    the raw packet data



57
58
59
60
# File 'lib/moleculer/packets/base.rb', line 57

def initialize(config, data = {})
  @data   = data
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



51
52
53
# File 'lib/moleculer/packets/base.rb', line 51

def config
  @config
end

Class Method Details

.inherited(other) ⇒ Object

this ensures that the packets get the accessors from the parent



14
15
16
# File 'lib/moleculer/packets/base.rb', line 14

def inherited(other)
  other.instance_variable_set(:@packet_accessors, other.packet_accessors.merge(packet_accessors))
end

.packet_accessorsObject



18
19
20
# File 'lib/moleculer/packets/base.rb', line 18

def packet_accessors
  @packet_accessors ||= {}
end

.packet_attr(name, default = :__not_defined__) ⇒ Object

Sets an accessor that fetches @data attributes



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/moleculer/packets/base.rb', line 24

def packet_attr(name, default = :__not_defined__)
  class_eval <<-ATTR, __FILE__, __LINE__ + 1
    def #{name}
      default = self.class.packet_accessors[:#{name}]
      if default != :__not_defined__
         return HashUtil.fetch(@data, :#{name}, default) unless default.is_a? Proc
         return HashUtil.fetch(@data, :#{name}, default.call(self))
      end
      return HashUtil.fetch(@data, :#{name})
    end
  ATTR
  packet_accessors[name] = default
end

.packet_nameObject



38
39
40
# File 'lib/moleculer/packets/base.rb', line 38

def packet_name
  name.split("::").last.upcase
end

Instance Method Details

#senderObject

The sender of the packet



49
# File 'lib/moleculer/packets/base.rb', line 49

packet_attr :sender, ->(packet) { packet.config.node_id }

#to_hObject



71
72
73
74
75
76
# File 'lib/moleculer/packets/base.rb', line 71

def to_h
  {
    ver:    ver,
    sender: sender,
  }
end

#topicString

The publishing topic for the packet. This is used to publish packets to the moleculer network. Override as needed.

Returns:

  • (String)

    the pub/sub topic to publish to



67
68
69
# File 'lib/moleculer/packets/base.rb', line 67

def topic
  "MOL.#{self.class.packet_name}"
end

#verObject

The protocol version



45
# File 'lib/moleculer/packets/base.rb', line 45

packet_attr :ver, "3"