Sha256: e65afc2d44947d6d8e649389932eac4374e57e2bedcc22f2179d44ce85b5c9a3

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

require 'forwardable'
require 'fileutils'

module TwitterFriendly
  class Cache
    extend Forwardable
    def_delegators :@client, :clear, :cleanup

    def initialize(*args)
      options = args.extract_options!

      path = options[:cache_dir] || File.join('.twitter_friendly', 'cache')
      FileUtils.mkdir_p(path) unless File.exists?(path)
      @client = ::ActiveSupport::Cache::FileStore.new(path, expires_in: 1.hour, race_condition_ttl: 5.minutes)
    end

    def fetch(method, user, options = {}, &block)
      key = CacheKey.gen(method, user, options.except(:args))
      super_operation = options[:args].length >= 2 && options[:args][1][:super_operation]

      block_result = nil
      blk =
          Proc.new do
            block_result = yield
            encode(block_result, args: options[:args])
          end

      fetch_result =
        if super_operation
          @client.fetch(key, tf_super_operation: super_operation, &blk)
        else
          @client.fetch(key, &blk)
        end

      block_result ? block_result : decode(fetch_result, args: options[:args])
    end

    private

    def encode(obj, options)
      Serializer.encode(obj, options)
    end

    def decode(str, options)
      Serializer.decode(str, options)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
twitter_friendly-0.2.0 lib/twitter_friendly/cache.rb