Class: Grenache::Message

Inherits:
Object
  • Object
show all
Defined in:
lib/grenache/message.rb

Overview

Store a single request information

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, payload, opts = {}, &block) ⇒ Message



8
9
10
11
12
13
14
15
# File 'lib/grenache/message.rb', line 8

def initialize(type, payload, opts={}, &block)
  @payload = payload
  @type = type
  @opts = opts
  @rid = opts[:rid]  if opts[:rid]
  @_ts = Time.now
  @block = block
end

Instance Attribute Details

#_tsObject

Returns the value of attribute _ts.



6
7
8
# File 'lib/grenache/message.rb', line 6

def _ts
  @_ts
end

#optsObject

Returns the value of attribute opts.



6
7
8
# File 'lib/grenache/message.rb', line 6

def opts
  @opts
end

#payloadObject

Returns the value of attribute payload.



6
7
8
# File 'lib/grenache/message.rb', line 6

def payload
  @payload
end

#typeObject

Returns the value of attribute type.



6
7
8
# File 'lib/grenache/message.rb', line 6

def type
  @type
end

Class Method Details

.parse(json) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/grenache/message.rb', line 17

def self.parse(json)
  rid,type,payload = Oj.load(json)
  if payload.nil?
    payload = type
    type = 'res'
  end
  new(type,payload, {rid:rid})
end

.req(type, payload) ⇒ Object



26
27
28
# File 'lib/grenache/message.rb', line 26

def self.req(type,payload)
  new(type,payload)
end

.response_to(req, payload) ⇒ Object



30
31
32
# File 'lib/grenache/message.rb', line 30

def self.response_to(req,payload)
  new('res',payload,{rid: req.rid})
end

Instance Method Details

#block_given?Boolean



42
43
44
# File 'lib/grenache/message.rb', line 42

def block_given?
  !!@block
end

#dump_payloadObject



58
59
60
# File 'lib/grenache/message.rb', line 58

def dump_payload
  @dump_payload ||= Oj.dump(payload)
end

#qhashObject



54
55
56
# File 'lib/grenache/message.rb', line 54

def qhash
  "#{type}#{dump_payload}"
end

#request?Boolean



34
35
36
# File 'lib/grenache/message.rb', line 34

def request?
  @type != 'res'
end

#response?Boolean



38
39
40
# File 'lib/grenache/message.rb', line 38

def response?
  @type == 'res'
end

#ridObject



50
51
52
# File 'lib/grenache/message.rb', line 50

def rid
  @rid ||= SecureRandom.uuid
end

#to_jsonObject



62
63
64
65
66
67
68
# File 'lib/grenache/message.rb', line 62

def to_json
  if response?
    Oj.dump([rid,payload])
  else
    Oj.dump([rid,type,payload])
  end
end

#yield(params = {}) ⇒ Object



46
47
48
# File 'lib/grenache/message.rb', line 46

def yield(params={})
  @block.call(params)
end