Skip to content

Instantly share code, notes, and snippets.

@cfpg
Created March 6, 2010 02:23
Show Gist options
  • Save cfpg/323439 to your computer and use it in GitHub Desktop.
Save cfpg/323439 to your computer and use it in GitHub Desktop.
class Online
include MongoMapper::Document
key :ip, String, :required => true
key :page, String, :required => true
key :time, Integer, :required => true
before_save :delete_old_entries # Automatically delete old entries before saving a new one
def add_online(ip, page)
# Add/update new online user
person = Online.first(:ip => ip)
if person.to_s.empty? # Is this IP already on the DB?
online = Online.create({
:ip => ip,
:page => page,
:time => Time.new.to_i
})
online.save
else
person.page = page # Update :page to the currently viewed webpage
person.time = Time.new.to_i # Update :time for the current entry
person.save
end
end
def count_online(opts={})
page = opts[:page] || ""
if page.empty? # Count every user online
people = Online.count()
else # Count only users on X page
people = Online.count({:page => page})
end
return people # returns Integer
end
private
def delete_old_entries
time = Time.new.to_i
limit = 15 # Seconds to keep old entries alive
online = Online.delete_all(:time => {"$lt" => time-limit})
end
end
# On each page
online = Online.new
online.add_online("255.255.255.255", "/")
# Count only users on the site
online.count_online
# Count online users on "/profile/admin"
online.count_online({:page => "/profile/admin"})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment