Module: UsableHelpers

Included in:
Usable
Defined in:
lib/ubiquitous_user.rb

Instance Method Summary collapse

Instance Method Details

#userObject

Helper method to get the current user. It will always return a user but the user may not be in the database. If options is true, then the user will be in the database (although it may be a ghost user).



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ubiquitous_user.rb', line 33

def user
  # Find the user in the database if session[:user_id] is defined and @ubiquitous_user is not.
  @ubiquitous_user = UsableConfig::user_model_class.find_by_id(session[:user_id]) if session[:user_id] != nil and @ubiquitous_user == nil
  
  # Create a new user object if @ubiquitous_user is not defined.
  @ubiquitous_user = UsableConfig::user_model_class.send(UsableConfig::user_model_new) if @ubiquitous_user == nil
  
  # If the object is new, let's get ready to mark the user as logged in when saving.
  if @ubiquitous_user.new_record? or @ubiquitous_user.id != session[:user_id]
    controller = self
    # Read more about this technique on http://stackoverflow.com/questions/2495550/define-a-method-that-is-a-closure-in-ruby
    klass = class << @ubiquitous_user; self; end
    klass.send(:define_method, :after_save) do
      super
      controller.session[:user_id] = self.id
    end
  end
  
  return @ubiquitous_user
end

#user!Object

DEPRECATED: Please use user instead. Call user.save! if you really needed it saved.



56
57
58
59
# File 'lib/ubiquitous_user.rb', line 56

def user!
  warn "[DEPRECATION] use 'user' instead, call 'user.save!' if you really needed it saved"
  return user
end

#user_logged_in?Boolean

Helper method to check whether a user is logged in or not



62
63
64
65
# File 'lib/ubiquitous_user.rb', line 62

def user_logged_in?
  user_id = session[:user_id]
  user_id != nil and UsableConfig::user_model_class.find_by_id(user_id) != nil and session[:user_name] != nil
end