Sha256: 76442f843fe21c7a4410e6a53f9003484cc787b8d08849bc1b557fa0a59d3ef8

Contents?: true

Size: 1.67 KB

Versions: 32

Compression:

Stored size: 1.67 KB

Contents

require 'gh'
require 'thread'

module GH
  # Public: This class caches responses.
  class Cache < Wrapper
    # Public: Get/set cache to use. Compatible with Rails/ActiveSupport cache.
    attr_accessor :cache

    # Internal: Simple in-memory cache basically implementing a copying GC.
    class SimpleCache
      # Internal: Initializes a new SimpleCache.
      #
      # size - Number of objects to hold in cache.
      def initialize(size = 2048)
        @old, @new, @size, @mutex = {}, {}, size/2, Mutex.new
      end

      # Internal: Tries to fetch a value from the cache and if it doesn't exist, generates it from the
      # block given.
      def fetch(key)
        @mutex.synchronize { @old, @new = @new, {} if @new.size > @size } if @new.size > @size
        @new[key] ||= @old[key] || yield
      end

      # Internal: ...
      def clear
        @mutex.synchronize { @old, @new = {}, {} }
      end
    end

    # Internal: Initializes a new Cache instance.
    def setup(*)
      #self.cache ||= Rails.cache if defined? Rails.cache and defined? RAILS_CACHE
      #self.cache ||= ActiveSupport::Cache.lookup_store if defined? ActiveSupport::Cache.lookup_store
      self.cache ||= SimpleCache.new
      super
    end

    # Public: ...
    def reset
      super
      clear_partial or clear_all
    end

    private

    def fetch_resource(key)
      cache.fetch(prefixed(key)) { super }
    end

    def clear_partial
      return false unless cache.respond_to? :delete_matched
      pattern = "^" << Regexp.escape(prefixed(""))
      cache.delete_matched Regexp.new(pattern)
      true
    rescue NotImplementedError
      false
    end

    def clear_all
      cache.clear
    end
  end
end

Version data entries

32 entries across 32 versions & 2 rubygems

Version Path
gh-0.18.0 lib/gh/cache.rb
gh-0.17.0 lib/gh/cache.rb
gh-0.16.0 lib/gh/cache.rb
gh-0.16.0.beta1 lib/gh/cache.rb
gh-akerl-0.15.1.1 lib/gh/cache.rb
gh-akerl-0.15.1 lib/gh/cache.rb
gh-0.15.1 lib/gh/cache.rb
gh-0.15.0 lib/gh/cache.rb
gh-0.14.0 lib/gh/cache.rb
gh-0.13.3 lib/gh/cache.rb
gh-0.13.2 lib/gh/cache.rb
gh-0.13.1 lib/gh/cache.rb
gh-0.13.0 lib/gh/cache.rb
gh-0.12.4 lib/gh/cache.rb
gh-0.12.3 lib/gh/cache.rb
gh-0.12.2 lib/gh/cache.rb
gh-0.12.1 lib/gh/cache.rb
gh-0.12.0 lib/gh/cache.rb
gh-0.11.3 lib/gh/cache.rb
gh-0.11.2 lib/gh/cache.rb