FEATURE: rudimentary view tracking wired in

This commit is contained in:
Sam 2015-02-04 16:14:56 +11:00
parent e105f0965c
commit c150c55e2d
3 changed files with 65 additions and 8 deletions

View file

@ -60,8 +60,12 @@ module Middleware
@env["REQUEST_METHOD"] == "GET"
end
def has_auth_cookie?
CurrentUser.has_auth_cookie?(@env)
end
def cacheable?
!!(!CurrentUser.has_auth_cookie?(@env) && get?)
!!(!has_auth_cookie? && get?)
end
def cached
@ -110,9 +114,36 @@ module Middleware
@app = app
end
def self.log_request_on_site(env, helper=nil)
host = RailsMultisite::ConnectionManagement.host(env)
RailsMultisite::ConnectionManagement.with_hostname(host) do
log_request(env,helper)
end
end
def self.log_request(env,helper=nil)
helper ||= Helper.new(env)
type =
if helper.is_crawler?
:crawler
elsif helper.has_auth_cookie?
:logged_in
else
:anon
end
ApplicationRequest.increment!(type)
end
def call(env)
helper = Helper.new(env)
Scheduler::Defer.later "Track view" do
self.class.log_request_on_site(env,helper)
end
if helper.cacheable?
helper.cached or helper.cache(@app.call(env))
else

View file

@ -3,12 +3,33 @@ require_dependency "middleware/anonymous_cache"
describe Middleware::AnonymousCache::Helper do
def new_helper(env={})
Middleware::AnonymousCache::Helper.new({
def env(opts={})
{
"HTTP_HOST" => "http://test.com",
"REQUEST_URI" => "/path?bla=1",
"REQUEST_METHOD" => "GET"
}.merge(env))
"REQUEST_METHOD" => "GET",
"rack.input" => ""
}.merge(opts)
end
def new_helper(opts={})
Middleware::AnonymousCache::Helper.new(env(opts))
end
context "log_request" do
it "can log requests correctly" do
freeze_time Time.now
ApplicationRequest.clear_cache!
Middleware::AnonymousCache.log_request(env "HTTP_USER_AGENT" => "AdsBot-Google (+http://www.google.com/adsbot.html)")
Middleware::AnonymousCache.log_request(env)
ApplicationRequest.write_cache!
ApplicationRequest.crawler.first.count.should == 1
ApplicationRequest.anon.first.count.should == 1
end
end
context "cachable?" do

View file

@ -158,15 +158,20 @@ module RailsMultisite
@app = app
end
def call(env)
def self.host(env)
request = Rack::Request.new(env)
request['__ws'] || request.host
end
def call(env)
host = self.class.host(env)
begin
#TODO: add a callback so users can simply go to a domain to register it, or something
return [404, {}, ["not found"]] unless @@host_spec_cache[request.host]
return [404, {}, ["not found"]] unless @@host_spec_cache[host]
ActiveRecord::Base.connection_handler.clear_active_connections!
self.class.establish_connection(:host => request['__ws'] || request.host)
self.class.establish_connection(:host => host)
@app.call(env)
ensure
ActiveRecord::Base.connection_handler.clear_active_connections!