Sha256: bfe58850355918198f87c36cf8ff9bfee56cb50cd84ec5c3e4ddb2d3c809e7d8

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

require 'billy/handlers/handler'
require 'addressable/uri'
require 'cgi'

module Billy
  class CacheHandler
    extend Forwardable
    include Handler

    def_delegators :cache, :reset, :cached?

    def initialize
      @cache = Billy::Cache.instance
    end

    def handle_request(method, url, headers, body)
      method = method.downcase
      if handles_request?(method, url, headers, body)
        if (response = cache.fetch(method, url, body))
          Billy.log(:info, "puffing-billy: CACHE #{method} for '#{url}'")

          if Billy.config.dynamic_jsonp
            replace_response_callback(response, url)
          end

          return response
        end
      end
      nil
    end

    def handles_request?(method, url, headers, body)
      cached?(method, url, body)
    end

    private

    def replace_response_callback(response, url)
      request_uri = Addressable::URI.parse(url)
      if request_uri.query
        params = CGI::parse(request_uri.query)
        if params['callback'].any? and response[:content].match(/\w+\(/)
          response[:content].sub!(/\w+\(/, params['callback'].first + '(')
        end
      end
    end

    def cache
      @cache
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
puffing-billy-0.4.1 lib/billy/handlers/cache_handler.rb