Class: Startback::Event

Inherits:
Object
  • Object
show all
Defined in:
lib/startback/event.rb

Overview

An Event occuring a given context and having a type and attached data.

Event instances have String types that are by default unrelated to ruby classes. Also, this Event class has a ‘json` information contract that allows dumping & reloading them easily. A context or context_factory may be provided in dress world to reload the event context from data, but that logic is opaque to this class.

This class is intended to be subclassed if a more specific event protocol is wanted.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, data, context = nil) ⇒ Event

Returns a new instance of Event.



16
17
18
19
20
# File 'lib/startback/event.rb', line 16

def initialize(type, data, context = nil)
  @type = type.to_s
  @data = OpenStruct.new(data)
  @context = context
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



21
22
23
# File 'lib/startback/event.rb', line 21

def context
  @context
end

#dataObject (readonly)

Returns the value of attribute data.



21
22
23
# File 'lib/startback/event.rb', line 21

def data
  @data
end

#typeObject (readonly)

Returns the value of attribute type.



21
22
23
# File 'lib/startback/event.rb', line 21

def type
  @type
end

Class Method Details

.json(src, world = {}) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/startback/event.rb', line 23

def self.json(src, world = {})
  parsed = JSON.parse(src)
  context = if world[:context]
    world[:context]
  elsif world[:context_factory]
    world[:context_factory].call(parsed)
  end
  Event.new(parsed['type'], parsed['data'], context)
end

Instance Method Details

#to_json(*args, &bl) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/startback/event.rb', line 33

def to_json(*args, &bl)
  h = {
    type: self.type,
    data: data.to_h
  }
  h[:context] = context if context
  h.to_json(*args, &bl)
end