Permalink
Browse files

add `:strip_params` option for Caching middleware

  • Loading branch information...
1 parent 9f9ec14 commit 6756ffc73ff2ad02235b0646f6b1236aa921f8b1 @mislav committed Apr 1, 2011
Showing with 34 additions and 2 deletions.
  1. +1 −0 lib/faraday_stack.rb
  2. +18 −0 lib/faraday_stack/addressable_patch.rb
  3. +15 −2 lib/faraday_stack/caching.rb
@@ -1,6 +1,7 @@
# encoding: utf-8
require 'faraday'
require 'forwardable'
+require 'faraday_stack/addressable_patch'
module FaradayStack
extend Faraday::AutoloadHelper
@@ -0,0 +1,18 @@
+require 'addressable/uri'
+
+# fix `normalized_query` by sorting query key-value pairs
+# (rejected: https://github.com/sporkmonger/addressable/issues/28)
+class Addressable::URI
+ class << self
+ alias old_normalize_component normalize_component
+
+ def normalize_component(component, character_class = CharacterClasses::RESERVED + CharacterClasses::UNRESERVED)
+ normalized = old_normalize_component(component, character_class)
+ if character_class == Addressable::URI::CharacterClasses::QUERY
+ pairs = normalized.split('&').sort_by { |pair| pair[0, pair.index('=') || pair.length] }
+ normalized = pairs.join('&')
+ end
+ normalized
+ end
+ end
+end
@@ -2,9 +2,10 @@ module FaradayStack
class Caching < Faraday::Middleware
attr_reader :cache
- def initialize(app, cache = nil)
+ def initialize(app, cache = nil, options = {})
super(app)
@cache = cache || Proc.new.call
+ @options = options
end
def call(env)
@@ -23,7 +24,19 @@ def call(env)
end
def cache_key(env)
- env[:url].request_uri
+ url = env[:url]
+ if params_to_strip.any?
+ url = url.dup
+ url.query_values = url.query_values.reject { |k,| params_to_strip.include? k }
+ url.normalize!
+ else
+ url = url.normalize
+ end
+ url.request_uri
+ end
+
+ def params_to_strip
+ @params_to_strip ||= Array(@options[:strip_params]).map { |p| p.to_s }
end
def cache_on_complete(env)

0 comments on commit 6756ffc

Please sign in to comment.