Sha256: eed62ee025dc11fa92ea962327ce8c972e7ac6c306fa38c2ff1b9650be741748

Contents?: true

Size: 1.15 KB

Versions: 4

Compression:

Stored size: 1.15 KB

Contents

require 'securerandom'
require 'json'
require 'time'

module ConnectClient
  class Event

    @@RESERVED_PROPERTY_REGEX = /tp_.+/i

    attr_reader :data

    def initialize(data)
      event_data_defaults = { id: SecureRandom.uuid, timestamp: Time.now.utc.iso8601 }
      @data = event_data_defaults.merge(data)

      if (@data[:timestamp].respond_to? :iso8601)
        @data[:timestamp] = @data[:timestamp].iso8601
      end

      validate
    end

    def validate
      invalid_properties = @data.keys.grep(@@RESERVED_PROPERTY_REGEX)

      raise EventDataValidationError.new(invalid_properties) if invalid_properties.any?
    end

    def to_json(options = nil)
      @data.to_json
    end

    def to_s
      "Event Data: #{@data}"
    end
  end

  class EventDataValidationError < StandardError
    attr_reader :invalid_property_names

    def initialize(invalid_property_names)
      @invalid_property_names = invalid_property_names
    end

    def message
      messages = ['The following properties use the reserved prefix tp_:'] + @invalid_property_names.map do |property_name|
        "->#{property_name}"
      end
      messages.join "\n"
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
connect_client-0.1.6 lib/connect_client/event.rb
connect_client-0.1.5 lib/connect_client/event.rb
connect_client-0.1.4 lib/connect_client/event.rb
connect_client-0.1.3 lib/connect_client/event.rb