· 8 years ago · Mar 15, 2018, 06:36 AM
1# Code sample to determine if a user has been recently online
2# Using restful_authentication or acts_as_authenticated
3# By emili.parreno AT gmail.com // jaimeiniesta AT gmail.com
4
5## migration to add last_seen_at to users
6
7class AddLastSeenAtToUsers < ActiveRecord::Migration
8 def self.up
9 add_column :users, :last_seen_at, :datetime, :default => "2000-01-01"
10 end
11
12 def self.down
13 remove_column :users, :last_seen_at
14 end
15end
16
17## apps/controllers/application.rb
18
19class ApplicationController < ActionController::Base
20 before_filter :update_last_seen_at
21
22 def update_last_seen_at
23 if logged_in? and current_user.last_seen_at + 5.minutes < Time.now
24 @user = User.find(current_user.id)
25 @user.update_attribute("last_seen_at" ,Time.now)
26 end
27 end
28end
29
30## apps/models/user.rb
31
32class User < ActiveRecord::Base
33 def is_online?
34 last_seen_at + 5.minutes > Time.now
35 end
36end