Sha256: 3cd751a55fbc34193224ed1462baa8cf0418a57f21da315459317bc47e245f31

Contents?: true

Size: 1.23 KB

Versions: 4

Compression:

Stored size: 1.23 KB

Contents

require 'rack/utils'

module Rack::Cache
  class Key
    include Rack::Utils

    # Implement .call, since it seems like the "Rack-y" thing to do. Plus, it
    # opens the door for cache key generators to just be blocks.
    def self.call(request)
      new(request).generate
    end

    def initialize(request)
      @request = request
    end

    # Generate a normalized cache key for the request.
    def generate
      parts = []
      parts << @request.scheme << "://"
      parts << @request.host

      if @request.scheme == "https" && @request.port != 443 ||
          @request.scheme == "http" && @request.port != 80
        parts << ":" << @request.port.to_s
      end

      parts << @request.script_name
      parts << @request.path_info

      if qs = query_string
        parts << "?"
        parts << qs
      end

      parts.join
    end

  private
    # Build a normalized query string by alphabetizing all keys/values
    # and applying consistent escaping.
    def query_string
      return nil if @request.query_string.to_s.empty?

      @request.query_string.split(/[&;] */n).
        map { |p| p.split('=', 2).map{ |s| unescape(s) } }.
        sort.
        map { |k,v| "#{escape(k)}=#{escape(v)}" }.
        join('&')
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rack-cache-1.10.0 lib/rack/cache/key.rb
rack-cache-1.9.0 lib/rack/cache/key.rb
rack-cache-1.8.0 lib/rack/cache/key.rb
rack-cache-1.7.2 lib/rack/cache/key.rb