Sha256: ba449837ba8491e84cbf4bb7bb97cdd60cb2841ed37e70dd0188bd7c44958ced

Contents?: true

Size: 1.17 KB

Versions: 6

Compression:

Stored size: 1.17 KB

Contents

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

module Billy
  class CacheHandler
    extend Forwardable
    include Handler

    attr_reader :cache

    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? && response[:content].match(/\w+\(/)
          response[:content].sub!(/\w+\(/, params['callback'].first + '(')
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
puffing-billy-0.7.0 lib/billy/handlers/cache_handler.rb
puffing-billy-0.6.2 lib/billy/handlers/cache_handler.rb
puffing-billy-0.6.1 lib/billy/handlers/cache_handler.rb
puffing-billy-0.6.0 lib/billy/handlers/cache_handler.rb
puffing-billy-0.5.1 lib/billy/handlers/cache_handler.rb
puffing-billy-0.5.0 lib/billy/handlers/cache_handler.rb