April 13, 2011

toggle confirmable on and off

We are using the devise gem for the authentication of users in Socialite. The gem makes it ridiculously easy to manage our users.

One issue we had to solve was a way to toggle on and off the confirmable ability for our user model. Usually, to make the users confirmable or not, you would just add or remove the :confirmable symbol from the list of devise capabilities:


class User < ActiveRecord::Base
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
...
end


This works well usually but we need a way to toggle that capability at runtime. The solution is simple. We created an #after_initialize hook in which we initialized the confirmed_at attribute:




1 class User < ActiveRecord::Base
2 devise :database_authenticatable, :registerable, :confirmable,
3 :recoverable, :rememberable, :trackable, :validatable
4
5 def setup_default_values
6 self[:confirmed_at] ||= Time.now if !AppSettings.confirm_email_on_registration
7 end
8 end