From 426223dda01ce1dfced76179fd4fc30d70a132cc Mon Sep 17 00:00:00 2001 From: lest Date: Thu, 24 Nov 2011 21:42:58 +0300 Subject: [PATCH] timeout_in option can be a Proc object --- CHANGELOG.rdoc | 1 + lib/devise/models/timeoutable.rb | 15 +++++++++------ test/models/timeoutable_test.rb | 20 ++++++++++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.rdoc b/CHANGELOG.rdoc index 45e75b45..6de362e3 100644 --- a/CHANGELOG.rdoc +++ b/CHANGELOG.rdoc @@ -2,6 +2,7 @@ * enhancements * Add support for rails 3.1 new mass assignment conventions (by github.com/kirs) + * timeout_in option can be a Proc object (by github.com/lest) * bug fix * OmniAuth error message now shows the proper option (:strategy_class instead of :klass) diff --git a/lib/devise/models/timeoutable.rb b/lib/devise/models/timeoutable.rb index 08876818..343b09f0 100644 --- a/lib/devise/models/timeoutable.rb +++ b/lib/devise/models/timeoutable.rb @@ -23,18 +23,21 @@ module Devise # Checks whether the user session has expired based on configured time. def timedout?(last_access) return false if remember_exists_and_not_expired? - - last_access && last_access <= self.class.timeout_in.ago + + timeout_in = self.class.timeout_in + timeout_in = timeout_in.call(self) if timeout_in.respond_to?(:call) + + !timeout_in.nil? && last_access && last_access <= timeout_in.ago end - + private - + def remember_exists_and_not_expired? return false unless respond_to?(:remember_expired?) - + remember_created_at && !remember_expired? end - + module ClassMethods Devise::Models.config(self, :timeout_in) end diff --git a/test/models/timeoutable_test.rb b/test/models/timeoutable_test.rb index 12aad5e1..f9cb9cf8 100644 --- a/test/models/timeoutable_test.rb +++ b/test/models/timeoutable_test.rb @@ -14,6 +14,26 @@ class TimeoutableTest < ActiveSupport::TestCase assert_not new_user.timedout?(nil) end + test 'should accept timeout_in proc and provide user as argument' do + user = new_user + + timeout_in = proc do |obj| + assert_equal user, obj + 10.minutes + end + + swap Devise, :timeout_in => timeout_in do + assert user.timedout?(12.minutes.ago) + assert_not user.timedout?(8.minutes.ago) + end + end + + test 'should not be expired when timeout_in proc returns nil' do + swap Devise, :timeout_in => proc { nil } do + assert_not new_user.timedout?(10.hours.ago) + end + end + test 'fallback to Devise config option' do swap Devise, :timeout_in => 1.minute do user = new_user