Class: EventStream::Event

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

Overview

Events are immutable collections of fields with convenience methods for accessing and json serialization

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields) ⇒ Event

Returns a new instance of Event.

Parameters:

  • fields (Hash<Symbol, Object>)

    The attributes of this event



8
9
10
# File 'lib/event_stream/event.rb', line 8

def initialize(fields)
  @fields = Hash[fields.map { |k,v| [k.to_sym, v] }].freeze
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object



36
37
38
# File 'lib/event_stream/event.rb', line 36

def method_missing(method_name, *args)
  @fields.has_key?(method_name) ? @fields[method_name] : super
end

Class Method Details

.from_json(json_event) ⇒ Event

Parses an event object from JSON

Parameters:

  • json_event (String)

    The JSON event representation, such as created by ‘event.to_json`

Returns:



32
33
34
# File 'lib/event_stream/event.rb', line 32

def self.from_json(json_event)
  new(JSON.parse(json_event))
end

Instance Method Details

#[](key) ⇒ Object

An alternate field accessor

Parameters:

  • key (Symbol)

Returns:

  • (Object)


15
16
17
# File 'lib/event_stream/event.rb', line 15

def [](key)
  @fields[key.to_sym]
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/event_stream/event.rb', line 40

def respond_to_missing?(method_name, include_private = false)
  @fields.has_key?(method_name) || super
end

#to_hHash<Symbol, Object>

Returns:

  • (Hash<Symbol, Object>)


20
21
22
# File 'lib/event_stream/event.rb', line 20

def to_h
  @fields
end

#to_jsonString

Returns:

  • (String)


25
26
27
# File 'lib/event_stream/event.rb', line 25

def to_json
  JSON.dump(to_h)
end