lib/speed_gun/event.rb in speed_gun-1.0.0.rc1 vs lib/speed_gun/event.rb in speed_gun-2.0.0.pre.alpha.1

- old
+ new

@@ -1,72 +1,62 @@ +# frozen_string_literal: true +require 'securerandom' require 'speed_gun' class SpeedGun::Event - def self.from_hash(id, hash) - event = new( - hash['name'], - hash['payload'], - Time.at(hash['started_at']), - hash['finished_at'] ? Time.at(hash['finished_at']) : nil - ) - event.instance_variable_set(:@id, id) - - event - end - - # @return [String] event ID + # @return [String] Event ID attr_reader :id - - # @return [String] event name + # @return [String] Event name attr_reader :name - - # @return [Hashie::Mash] payload + # @return [Hash] Event payload attr_reader :payload - - # @return [Time] start time + # @return [Time] Started time of event attr_reader :started_at - - # @return [Time, nil] finish time + # @return [Time, nil] Finished time of event attr_reader :finished_at + attr_reader :children - # @param name [String] event name - # @param payload [Hash] payload - # @param started_at [Time] start time - # @param finished_at [Time, nil] finish time - # @return [SpeedGun::Event] instance of SpeedGun::Event + def self.from_hash(hash, id = nil) + new( + hash['name'], + hash['payload'], + Time.at(hash['started_at'].to_f), + hash['finished_at'] ? Time.at(hash['finished_at']) : nil + ).tap do |event| + event.instance_variable_set(:@id, id) if id + end + end + def initialize(name, payload = {}, started_at = Time.now, finished_at = nil) @id = SecureRandom.uuid - @name = name - @payload = Hashie::Mash.new(payload) + @name = name.to_s + @payload = payload @started_at = started_at @finished_at = finished_at + @children = [] end - # Finish event - # - # @return [Time] finish time def finish! @finished_at = Time.now end - # @return [true, false] true if the event is finished def finished? - !@finished_at.nil? + @finished_at end - # Time duration of the event - # - # @return [Float] a duration of the event + def roughly_finished_at + finished_at || started_at + end + def duration - finished? ? finished_at.to_f - started_at.to_f : -1 + finished_at ? finished_at.to_f - started_at.to_f : 0 end def to_hash { 'name' => name, 'payload' => payload, 'started_at' => started_at.to_f, - 'finished_at' => finished? ? finished_at.to_f : nil, - 'duration' => duration + 'finished_at' => finished? ? finished_at.to_f : nil } end end