Skip to content
Snippets Groups Projects
autoexpire_cache_dalli.rb 1.26 KiB
Newer Older
  • Learn to ignore specific revisions
  • # This class implements a cache with simple delegation to the the Dalli Memcached client
    # https://github.com/mperham/dalli
    #
    # A TTL is set on initialization
    # Dalli is set up as on Heroku using the Memcachier gem.
    # https://devcenter.heroku.com/articles/memcachier#ruby
    # On other setups you might have to specify your Memcached server in Dalli::Client.new
    
    
    class AutoexpireCacheDalli
    
      def initialize(ttl = 86400)
        @keys = 'GeocoderDalliClientKeys'
        @store = Dalli::Client.new(:expires_in => ttl)
      end
    
    
      def [](url)
        res = @store.get(url)
    
      def []=(url, value)
    
          key_cache_add(url) if @store.add(key, YAML::dump(value))
    
      def del(url)
        key_cache_delete(url) if @store.delete(key)
    
      end
    
      private
    
      def key_cache
        the_keys = @store.get(@keys)
        if the_keys.nil?
          @store.add(@keys, YAML::dump([]))
          []
        else
          YAML::load(the_keys)
        end
      end
    
      def key_cache_add(key)
        @store.replace(@keys, YAML::dump(key_cache << key))
      end
    
      def key_cache_delete(key)
        tmp = key_cache
        tmp.delete(key)
        @store.replace(@keys, YAML::dump(tmp))
      end
    end