Sha256: 03fc658f40efbacb8ef003e9d36dc5dda216f835d4259cf96be8a9767147f452

Contents?: true

Size: 639 Bytes

Versions: 8

Compression:

Stored size: 639 Bytes

Contents

module ZendeskAPI
  # http://codesnippets.joyent.com/posts/show/12329
  class ZendeskAPI::LRUCache
    attr_accessor :size

    def initialize(size = 10)
      @size = size
      @store = {}
      @lru = []
    end

    def write(key, value)
      @store[key] = value
      set_lru(key)
      @store.delete(@lru.pop) if @lru.size > @size
      value
    end

    def read(key)
      set_lru(key)
      @store[key]
    end

    def fetch(key)
      if @store.has_key? key
        read key
      else
        write key, yield
      end
    end

    private

    def set_lru(key)
      @lru.unshift(@lru.delete(key) || key)
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
zendesk_api-0.1.7 lib/zendesk_api/lru_cache.rb
zendesk_api-0.1.6 lib/zendesk_api/lru_cache.rb
zendesk_api-0.1.5 lib/zendesk_api/lru_cache.rb
zendesk_api-0.1.4 lib/zendesk_api/lru_cache.rb
zendesk_api-0.1.3 lib/zendesk_api/lru_cache.rb
zendesk_api-0.1.2 lib/zendesk_api/lru_cache.rb
zendesk_api-0.1.1 lib/zendesk_api/lru_cache.rb
zendesk_api-0.0.9 lib/zendesk_api/lru_cache.rb