Sha256: 3d680e5d31f09c9ec0d669b8493ef9fd7d3810e87eac8c41040a6c8b3c560784

Contents?: true

Size: 870 Bytes

Versions: 6

Compression:

Stored size: 870 Bytes

Contents

require 'mutex_m'
module Phoenix
  class Inbox
    # Read it or forget it

    include Mutex_m
    attr_reader :ttl, :data
    def initialize(ttl:)
      @ttl = ttl
      @bucket = Time.now.to_i / ttl
      @data = Hash.new { |h, k| h[k] = {} }
      super()
    end

    def push(key, val)
      synchronize do
        ts = current_timestamp
        (data[ts][key] = val).tap do
          if data.keys.size >= 3
            data.delete_if { |key, _| key < (ts - 1) }
          end
        end
      end
    end

    alias_method :[]=, :push

    def pop(key)
      synchronize do
        ts = current_timestamp
        data[ts - 1].delete(key) { data[ts].delete(key) { yield }}
      end
    end

    alias_method :delete, :pop

    def key?(key)
      data.values.any? { |v| v.key?(key) }
    end

    def current_timestamp
      Time.now.to_i / ttl
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
yatapp-0.5.5 lib/yatapp/inbox.rb
yatapp-0.5.4 lib/yatapp/inbox.rb
yatapp-0.5.3 lib/yatapp/inbox.rb
yatapp-0.5.2 lib/yatapp/inbox.rb
yatapp-0.5.1 lib/yatapp/inbox.rb
yatapp-0.5.0 lib/yatapp/inbox.rb