Class: Rubyists::Leopard::MessageWrapper
- Inherits:
-
Object
- Object
- Rubyists::Leopard::MessageWrapper
- Defined in:
- lib/leopard/message_wrapper.rb
Overview
Wraps a raw NATS message with parsed payload and convenience response helpers.
Instance Attribute Summary collapse
- #data ⇒ NATS::Message, Object readonly
-
#headers ⇒ Hash
The headers from the NATS message.
- #raw ⇒ NATS::Message, Object readonly
Instance Method Summary collapse
-
#initialize(nats_msg) ⇒ MessageWrapper
constructor
A new instance of MessageWrapper.
-
#parse_data(raw) ⇒ Object
private
Parses the raw data from the NATS message.
- #respond(payload) ⇒ void
- #respond_with_error(err) ⇒ void
-
#serialize(obj) ⇒ String
private
Serializes the object to a JSON string if it is not already a string.
Constructor Details
#initialize(nats_msg) ⇒ MessageWrapper
Returns a new instance of MessageWrapper.
24 25 26 27 28 |
# File 'lib/leopard/message_wrapper.rb', line 24 def initialize(nats_msg) @raw = nats_msg @data = parse_data(nats_msg.data) @headers = nats_msg.header.to_h end |
Instance Attribute Details
#data ⇒ NATS::Message, Object (readonly)
16 |
# File 'lib/leopard/message_wrapper.rb', line 16 attr_reader :raw, :data |
#headers ⇒ Hash
Returns The headers from the NATS message.
21 22 23 |
# File 'lib/leopard/message_wrapper.rb', line 21 def headers @headers end |
#raw ⇒ NATS::Message, Object (readonly)
16 17 18 |
# File 'lib/leopard/message_wrapper.rb', line 16 def raw @raw end |
Instance Method Details
#parse_data(raw) ⇒ Object (private)
Parses the raw data from the NATS message. Assumes the data is in JSON format. If parsing fails, it returns the raw string.
54 55 56 57 58 |
# File 'lib/leopard/message_wrapper.rb', line 54 def parse_data(raw) JSON.parse(raw) rescue JSON::ParserError raw end |
#respond(payload) ⇒ void
This method returns an undefined value.
33 34 35 36 |
# File 'lib/leopard/message_wrapper.rb', line 33 def respond(payload) raw.header = headers unless headers.empty? raw.respond(serialize(payload)) end |
#respond_with_error(err) ⇒ void
This method returns an undefined value.
41 42 43 |
# File 'lib/leopard/message_wrapper.rb', line 41 def respond_with_error(err, &) raw.respond_with_error(err, &) end |
#serialize(obj) ⇒ String (private)
Serializes the object to a JSON string if it is not already a string.
64 65 66 |
# File 'lib/leopard/message_wrapper.rb', line 64 def serialize(obj) obj.is_a?(String) ? obj : JSON.generate(obj) end |