An approximation that might be good enough is to maintain a field in the users table called last_seen_at. Update it at each request in a high-priority filter. Then define to be online using a time window, say 3 minutes:
class User
def online?
Time.now - last_seen_at < 3.minutes
end
end
You could also include an Ajax function in each page that hits a "I'm
still here" URL on a timer, so you can tell if they've still got your
page open even if they're not requesting new pages. But, that
demonstrates that Xavier's assertion that "online is an ill-defined
concept" is definitely true. Are they online if they opened your page
12 hours ago and haven't been near their computer since? So maybe the
function only runs up to N times and then stops unless the page
refreshes or changes . . .
But in the real world, if you want to know how many (most?) popular
sites actually accomplish this - MySpace for example - they just use
Userplane to do it for them. They've already figured it all out.