diff --git a/app/models/user_stat.rb b/app/models/user_stat.rb index bb86ec4c2..2fde32179 100644 --- a/app/models/user_stat.rb +++ b/app/models/user_stat.rb @@ -55,15 +55,27 @@ class UserStat < ActiveRecord::Base MAX_TIME_READ_DIFF = 100 # attempt to add total read time to user based on previous time this was called def update_time_read! - last_seen_key = "user-last-seen:#{id}" - last_seen = $redis.get(last_seen_key) - if last_seen.present? + if last_seen = last_seen_cached diff = (Time.now.to_f - last_seen.to_f).round if diff > 0 && diff < MAX_TIME_READ_DIFF UserStat.where(user_id: id, time_read: time_read).update_all ["time_read = time_read + ?", diff] end end - $redis.set(last_seen_key, Time.now.to_f) + cache_last_seen(Time.now.to_f) + end + + private + + def last_seen_key + @last_seen_key ||= "user-last-seen:#{id}" + end + + def last_seen_cached + $redis.get(last_seen_key) + end + + def cache_last_seen(val) + $redis.set(last_seen_key, val) end end diff --git a/spec/models/user_stat_spec.rb b/spec/models/user_stat_spec.rb index be4516f12..4e65a7a13 100644 --- a/spec/models/user_stat_spec.rb +++ b/spec/models/user_stat_spec.rb @@ -77,14 +77,14 @@ describe UserStat do let(:stat) { user.user_stat } it 'makes no changes if nothing is cached' do - $redis.expects(:get).with("user-last-seen:#{user.id}").returns(nil) + stat.expects(:last_seen_cached).returns(nil) stat.update_time_read! stat.reload stat.time_read.should == 0 end it 'makes a change if time read is below threshold' do - $redis.expects(:get).with("user-last-seen:#{user.id}").returns(Time.now - 10.0) + stat.expects(:last_seen_cached).returns(Time.now - 10) stat.update_time_read! stat.reload stat.time_read.should == 10 @@ -92,7 +92,7 @@ describe UserStat do it 'makes no change if time read is above threshold' do t = Time.now - 1 - UserStat::MAX_TIME_READ_DIFF - $redis.expects(:get).with("user-last-seen:#{user.id}").returns(t) + stat.expects(:last_seen_cached).returns(t) stat.update_time_read! stat.reload stat.time_read.should == 0