· 8 years ago · Apr 25, 2018, 02:56 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 current_user.update_attribute("last_seen_at" ,Time.now)
25 end
26 end
27end
28
29## apps/models/user.rb
30
31class User < ActiveRecord::Base
32 def is_online?
33 last_seen_at + 5.minutes > Time.now
34 end
35end