lib/kamerling/message.rb in kamerling-0.0.2 vs lib/kamerling/message.rb in kamerling-0.0.3
- old
+ new
@@ -1,47 +1,60 @@
-module Kamerling class Message
- UnknownType = Class.new RuntimeError
+require 'equalizer'
+require_relative 'uuid'
- def self.[] client: req(:client), payload: req(:payload),
- project: req(:project), task: req(:task), type: req(:type)
- new "#{type}\0\0\0\0\0\0\0\0\0\0\0\0" + UUID.bin(client.uuid) +
- UUID.bin(project.uuid) + UUID.bin(task.uuid) + payload
- end
+module Kamerling
+ class Message
+ KNOWN_TYPES = %i(DATA PING RGST RSLT)
+ UnknownType = Class.new(RuntimeError)
- def initialize raw
- @raw = raw
- type = raw[0..3]
- known_types = %w(DATA PING RGST RSLT)
- fail UnknownType, type unless known_types.include? type or type.empty?
- end
+ include Equalizer.new(:raw)
- def == other
- raw == other.raw
- end
+ def self.build(client:, payload:, project:, task:, type:)
+ new([type, "\0\0\0\0\0\0\0\0\0\0\0\0", UUID.bin(client.uuid),
+ UUID.bin(project.uuid), UUID.bin(task.uuid), payload].join)
+ end
- def client_uuid
- UUID[raw[16..31]]
- end
+ def self.parse(raw)
+ new(raw)
+ end
- def payload
- raw[64..-1]
- end
+ def initialize(raw)
+ @raw = raw
+ fail UnknownType, type unless KNOWN_TYPES.include?(type) or type.empty?
+ end
- def project_uuid
- UUID[raw[32..47]]
- end
+ def client_type
+ raw[4..7].to_sym
+ end
- def task_uuid
- UUID[raw[48..63]]
- end
+ def client_uuid
+ UUID[raw[16..31]]
+ end
- def to_s
- raw
- end
+ def payload
+ raw[64..-1]
+ end
- def type
- raw[0..3].to_sym
- end
+ def project_uuid
+ UUID[raw[32..47]]
+ end
- attr_reader :raw
- private :raw
-end end
+ def task_uuid
+ UUID[raw[48..63]]
+ end
+
+ def to_hex
+ raw.unpack('H*').first.scan(/../).join(' ')
+ end
+
+ def to_s
+ raw
+ end
+
+ def type
+ raw[0..3].to_sym
+ end
+
+ attr_reader :raw
+ protected :raw
+ end
+end