Skip to content

Instantly share code, notes, and snippets.

@sco
Created September 23, 2010 18:34
Show Gist options
  • Save sco/594109 to your computer and use it in GitHub Desktop.
Save sco/594109 to your computer and use it in GitHub Desktop.
class VisitorStats
def initialize
@redis = Redis.new
end
# every time there's a hit, increment a counter for the
# day and week, and add the session id to a set of unique
# vistitors for the day/week
def hit(session_id)
today = Date.today
@redis.incr("hit_count:day:" + day_key(today))
@redis.sadd("visitors:day:" + day_key(today), session_id)
@redis.incr("hits_count:week:" + week_key(today))
@redis.sadd("visitors:week:" + week_key(today), session_id)
end
def week_hits(date)
@redis.get("hit_count:week:" + week_key(date))
end
def day_hits(date)
@redis.get("hit_count:day:" + day_key(date))
end
def day_visitors(date)
@redis.get("visitor_count:day:" + day_key(date)) || @redis.scard("visitors:day:" + day_key(date))
end
def week_visitors(date)
@redis.get("visitor_count:week:" + week_key(date)) || @redis.scard("visitors:week:" + week_key(date))
end
# after the day is over, archive the visitor count and delete the set of session ids
def archive_day(date)
@redis.set("visitor_count:day:" + day_key(date), @redis.scard("visitors:day:" + day_key(date)))
@redis.del("visitors:day:" + day_key(date))
end
# after the week is over, archive the visitor count and delete the set of session ids
def archive_week(date)
@redis.set("visitor_count:week:" + week_key(date), @redis.scard("visitors:week:" + week_key(date)))
@redis.del("visitors:week:" + week_key(date))
end
private
def day_key(date)
date.strftime('%Y-%m-%d')
end
def week_key(date)
date.strftime('%Y-%W')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment