Created
March 6, 2011 18:58
-
-
Save tobi/857543 to your computer and use it in GitHub Desktop.
What would a stats server backed by redis look like?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'redis' | |
$redis = Redis.new | |
class Request | |
def referrer | |
'http://www.google.com/search?q=Shopify+Store' | |
end | |
def search_terms | |
'Shopify Store' | |
end | |
def search_engine | |
'Google' | |
end | |
def object | |
'products-1' | |
end | |
def category | |
'organic' | |
end | |
def new_session? | |
true | |
end | |
end | |
class ShopStats | |
def initialize(shop_id) | |
@shop_id = shop_id | |
@now = Time.now | |
end | |
def global | |
ShopStats.new('global') | |
end | |
def incr(*args) | |
options = if args.last.is_a?(Hash) | |
args.pop | |
end | |
term = args.join(":") | |
$redis.incr "#{@now.year}/#{@shop_id}/#{term}" | |
$redis.incr "#{@now.year}/#{@now.month}/#{@shop_id}/#{term}" | |
$redis.incr "#{@now.year}/#{@now.month}/#{@now.day}/#{@shop_id}/#{term}" | |
$redis.incr "#{@now.year}/#{@now.month}/#{@now.day}/#{@now.hour}/#{@shop_id}/#{term}" | |
if options | |
raise ArgumentError, 'expecting two arguments' unless args.length == 2 | |
$redis.sadd "#{@now.year}/#{@now.month}/#{@now.day}/#{@now.hour}/#{@shop_id}/#{args[0]}", args[1] | |
end | |
end | |
end | |
class GlobalStats < ShopStats | |
def initialize | |
super('global') | |
end | |
end | |
request = Request.new | |
redis = Redis.new | |
now = Time.now | |
shop_id = 100014 | |
stats = ShopStats.new(shop_id) | |
stats.global.incr 'hits' | |
stats.incr 'hits' | |
if request.object | |
stats.incr 'objects', request.object | |
end | |
if request.new_session? | |
stats.incr 'visits' | |
stats.incr 'traffic', request.category | |
stats.incr 'referrer', request.referrer, :collection => true if request.referrer | |
stats.incr 'search-engines', request.search_engine, :collection => true if request.search_engine | |
stats.incr 'search-terms', request.search_terms, :collection => true if request.search_terms | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment