Class: SkyDB::Event

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Event

Initializes the event.



10
11
12
13
# File 'lib/skydb/event.rb', line 10

def initialize(options={})
  self.timestamp = options[:timestamp] || DateTime.now
  self.data = options[:data] || {}
end

Instance Attribute Details

#dataObject

The data associated with the event.



26
27
28
# File 'lib/skydb/event.rb', line 26

def data
  @data
end

#timestampObject

The moment the event occurred.



23
24
25
# File 'lib/skydb/event.rb', line 23

def timestamp
  @timestamp
end

Instance Method Details

#as_json(*a) ⇒ Object



59
# File 'lib/skydb/event.rb', line 59

def as_json(*a); return to_hash(*a); end

#formatted_timestampObject

The timestamp as ISO8601 formatted string with fractional seconds.



29
30
31
# File 'lib/skydb/event.rb', line 29

def formatted_timestamp()
  return SkyDB.format_timestamp(timestamp)
end

#from_hash(hash, *a) ⇒ Object

Decodes a hash into a event.



53
54
55
56
57
# File 'lib/skydb/event.rb', line 53

def from_hash(hash, *a)
  self.timestamp = !hash.nil? ? parse_timestamp(hash['timestamp']) : Time.now.utc.to_datetime()
  self.data = !hash.nil? ? hash['data'] : {}
  return self
end

#parse_timestamp(str) ⇒ DateTime

Parses an ISO8601 date string with fractional seconds.

Parameters:

  • str (String)

    The date string to parse.

Returns:

  • (DateTime)

    The parsed date.



71
72
73
74
75
76
77
78
79
# File 'lib/skydb/event.rb', line 71

def parse_timestamp(str)
  # Try to parse with fractional seconds first and then fallback to
  # a regular ISO8601 format.
  begin
    return DateTime.strptime(str, '%Y-%m-%dT%H:%M:%S.%NZ')
  rescue ArgumentError
    return DateTime.strptime(str, '%Y-%m-%dT%H:%M:%SZ')
  end
end

#to_hash(*a) ⇒ Object

Encodes the event into a hash.



45
46
47
48
49
50
# File 'lib/skydb/event.rb', line 45

def to_hash(*a)
  {
    'timestamp' => formatted_timestamp,
    'data' => data
  }
end

#to_json(*a) ⇒ Object



60
# File 'lib/skydb/event.rb', line 60

def to_json(*a); return as_json(*a).to_json; end