BUGFIX: web crawlers messing with anon caching

This commit is contained in:
Sam 2014-04-29 10:48:09 +10:00
parent ba683bc611
commit 35952055e2
2 changed files with 33 additions and 6 deletions

View File

@ -1,4 +1,5 @@
require_dependency "mobile_detection" require_dependency "mobile_detection"
require_dependency "crawler_detection"
module Middleware module Middleware
class AnonymousCache class AnonymousCache
@ -8,6 +9,9 @@ module Middleware
end end
class Helper class Helper
USER_AGENT = "HTTP_USER_AGENT".freeze
RACK_SESSION = "rack.session".freeze
def initialize(env) def initialize(env)
@env = env @env = env
end end
@ -19,18 +23,29 @@ module Middleware
def is_mobile? def is_mobile?
@is_mobile ||= @is_mobile ||=
begin begin
session = @env["rack.session"] session = @env[RACK_SESSION]
# don't initialize params until later otherwise # don't initialize params until later otherwise
# you get a broken params on the request # you get a broken params on the request
params = {} params = {}
user_agent = @env["HTTP_USER_AGENT"] user_agent = @env[USER_AGENT]
MobileDetection.resolve_mobile_view!(user_agent,params,session) ? :true : :false MobileDetection.resolve_mobile_view!(user_agent,params,session) ? :true : :false
end == :true end
@is_mobile == :true
end
def is_crawler?
@is_crawler ||=
begin
user_agent = @env[USER_AGENT]
CrawlerDetection.crawler?(user_agent) ? :true : :false
end
@is_crawler == :true
end end
def cache_key def cache_key
@cache_key ||= "ANON_CACHE_#{@env["HTTP_HOST"]}#{@env["REQUEST_URI"]}|m=#{is_mobile?}" @cache_key ||= "ANON_CACHE_#{@env["HTTP_HOST"]}#{@env["REQUEST_URI"]}|m=#{is_mobile?}|c=#{is_crawler?}"
end end
def cache_key_body def cache_key_body

View File

@ -30,15 +30,27 @@ describe Middleware::AnonymousCache::Helper do
new_helper("ANON_CACHE_DURATION" => 10) new_helper("ANON_CACHE_DURATION" => 10)
end end
let!(:crawler) do
new_helper("ANON_CACHE_DURATION" => 10, "HTTP_USER_AGENT" => "AdsBot-Google (+http://www.google.com/adsbot.html)")
end
after do after do
helper.clear_cache helper.clear_cache
crawler.clear_cache
end end
it "returns cached data for cached requests" do it "returns cached data for cached requests" do
helper.is_mobile = true helper.is_mobile = true
helper.cached.should be_nil helper.cached.should be_nil
helper.cache([200, {"HELLO" => "WORLD"}, ["hello ", "world"]]) helper.cache([200, {"HELLO" => "WORLD"}, ["hello ", "my world"]])
helper.cached.should == [200, {"HELLO" => "WORLD"}, ["hello world"]]
helper = new_helper("ANON_CACHE_DURATION" => 10)
helper.is_mobile = true
helper.cached.should == [200, {"HELLO" => "WORLD"}, ["hello my world"]]
crawler.cached.should be_nil
crawler.cache([200, {"HELLO" => "WORLD"}, ["hello ", "world"]])
crawler.cached.should == [200, {"HELLO" => "WORLD"}, ["hello world"]]
end end
end end