Skip to content

Instantly share code, notes, and snippets.

@utilityboy
Created July 1, 2016 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utilityboy/d41522d6b0e748eacb0c4ca775ba3a52 to your computer and use it in GitHub Desktop.
Save utilityboy/d41522d6b0e748eacb0c4ca775ba3a52 to your computer and use it in GitHub Desktop.
module Event
class BaseEvent
attr_reader :id
attr_reader :stream_id
attr_reader :event_id
attr_reader :payload
attr_reader :metadata
def initialize(id: nil, stream_id: nil, event_id: SecureRandom.uuid, payload: {}, metadata: {})
@id = id
@stream_id = stream_id
@event_id = event_id
@payload = payload
@metadata = metadata
@metadata[:timestamp] ||= Time.current
validate
end
def to_hash
{
stream_id: stream_id,
event_id: event_id,
event_type: self.class.name,
payload: payload,
metadata: metadata
}
end
def validate
raise ArgumentError, 'BaseEvent: missing stream_id' if stream_id.nil?
# The event_id attribute gets initialized to a RFC 4122 random UUID,
# which has a hex-grouped-with-hyphens representation like:
#
# example: 2d931510-d99f-494a-8c67-87feb05e1594
# counts: 12345678 1234 1234 1234 123456789012
uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
raise ArgumentError, 'BaseEvent: invalid stream_id' unless stream_id =~ uuid
raise ArgumentError, 'BaseEvent: invalid event_id' unless event_id =~ uuid
begin
DateTime.parse(timestamp) unless timestamp.is_a?(Time)
rescue ArgumentError
raise ArgumentError, 'BaseEvent: invalid timestamp'
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment