Sha256: bc3a1baa4f7db57930918c7b8afc6e98cfe8ed7824f4dd1b4e4f2b7ee2a87b37

Contents?: true

Size: 1.2 KB

Versions: 16

Compression:

Stored size: 1.2 KB

Contents

# frozen_string_literal: true

require 'active_support/time'

module Zenaton
  module Traits
    # Module to calculate duration between events
    module WithDuration
      # @return [Integer, NilClass] Duration in seconds
      def _get_duration
        return unless @buffer
        now, now_dup = _init_now_then
        @buffer.each do |time_unit, time_value|
          now_dup = _apply_duration(time_unit, time_value, now_dup)
        end
        diff_in_seconds(now, now_dup)
      end

      %i[seconds minutes hours days weeks months years].each do |method_name|
        define_method method_name do |value = 1|
          _push(method_name, value)
          self
        end
      end

      private

      def _init_now_then
        Time.zone = self.class.class_variable_get(:@@_timezone) || 'UTC'
        now = Time.zone.now
        Time.zone = nil # Resets time zone
        [now, now.dup]
      end

      def _push(method_name, value)
        @buffer ||= {}
        @buffer[method_name] = value
      end

      def _apply_duration(time_unit, time_value, time)
        time + time_value.send(time_unit)
      end

      def diff_in_seconds(before, after)
        (after - before).to_i
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
zenaton-0.6.0 lib/zenaton/traits/with_duration.rb
zenaton-0.5.3 lib/zenaton/traits/with_duration.rb
zenaton-0.5.2 lib/zenaton/traits/with_duration.rb
zenaton-0.5.1 lib/zenaton/traits/with_duration.rb
zenaton-0.5.0 lib/zenaton/traits/with_duration.rb
zenaton-0.4.2 lib/zenaton/traits/with_duration.rb
zenaton-0.4.1 lib/zenaton/traits/with_duration.rb
zenaton-0.4.0 lib/zenaton/traits/with_duration.rb
zenaton-0.3.1 lib/zenaton/traits/with_duration.rb
zenaton-0.3.0 lib/zenaton/traits/with_duration.rb
zenaton-0.2.3 lib/zenaton/traits/with_duration.rb
zenaton-0.2.2 lib/zenaton/traits/with_duration.rb
zenaton-0.2.1 lib/zenaton/traits/with_duration.rb
zenaton-0.2.0 lib/zenaton/traits/with_duration.rb
zenaton-0.1.1 lib/zenaton/traits/with_duration.rb
zenaton-0.1.0 lib/zenaton/traits/with_duration.rb