class IORequest::Message
Single message. Either request or response.
Constants
- TYPES
Types of messages.
Attributes
data[R]
@return [Hash]
id[R]
@return [Utility::ExtendedID]
to[R]
@return [Utility::ExtendedID]
type[R]
@return [Symbol]
Public Class Methods
new(data, type: :request, id: nil, to: nil)
click to toggle source
Create new message. @param data [Hash] @param type [Symbol] one of {TYPES} member. @param id [Utility::ExtendedID, String, nil] only should be filled if
message is received from outside.
@param to [Utility::ExtendedID, String, nil] if message is response, it
should include integer of original request.
# File lib/io_request/message.rb, line 17 def initialize(data, type: :request, id: nil, to: nil) @data = data @type = type @id = id.nil? ? extended_id : Utility::ExtendedID.from(id) @to = to.nil? ? nil : Utility::ExtendedID.from(to) check_data end
read_from(io_r)
click to toggle source
@param io_r [:read] @return [Message]
# File lib/io_request/message.rb, line 83 def self.read_from(io_r) size = io_r.read(2)&.unpack1('S') || 0 raise ZeroSizeMessageError if size.zero? json_string = io_r.read(size).unpack1("a#{size}") msg = JSON.parse(json_string, symbolize_names: true) Message.new(msg[:data], id: msg[:id], type: msg[:type].to_sym, to: msg[:to]) end
Public Instance Methods
check_data()
click to toggle source
Check data correctness.
# File lib/io_request/message.rb, line 27 def check_data raise '@data is not a hash' unless @data.is_a? Hash raise 'incorrect @type' unless TYPES.include? @type raise 'incorrect @id' unless @id.is_a? Utility::ExtendedID raise '@to not specified for response' if response? && @to.nil? end
request?()
click to toggle source
@return [Boolean]
# File lib/io_request/message.rb, line 47 def request? @type == :request end
response?()
click to toggle source
@return [Boolean]
# File lib/io_request/message.rb, line 52 def response? @type == :response end
to_binary()
click to toggle source
@return [String] binary data to be passed over IO.
# File lib/io_request/message.rb, line 66 def to_binary json_string = JSON.generate({ id: @id.to_s, type: @type.to_s, to: @to.to_s, data: @data }) [json_string.size, json_string].pack("Sa#{json_string.size}") end
to_s()
click to toggle source
@return [String]
# File lib/io_request/message.rb, line 57 def to_s if request? "Request##{@id}: #{data}" else "Response##{@id}: #{data} to ##{@to}" end end
write_to(io_w)
click to toggle source
@param io_w [:write]
# File lib/io_request/message.rb, line 77 def write_to(io_w) io_w.write(to_binary) end