Class: Ramaze::Helper::User::Wrapper

Inherits:
BlankSlate show all
Defined in:
lib/ramaze/helper/user.rb

Overview

Wrapper for the ever-present “user” in your application. It wraps around an arbitrary instance and worries about authentication and storing information about the user in the session.

In order to not interfere with the wrapped instance/model we start our methods with an underscore. Suggestions on improvements as usual welcome.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, callback) ⇒ Wrapper

Returns a new instance of Wrapper.



57
58
59
60
61
# File 'lib/ramaze/helper/user.rb', line 57

def initialize(model, callback)
  @_model, @_callback = model, callback
  @_user = nil
  
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args, &block) ⇒ Object

Refer everything not known



103
104
105
106
# File 'lib/ramaze/helper/user.rb', line 103

def method_missing(meth, *args, &block)
  return unless _user
  _user.send(meth, *args, &block)
end

Instance Attribute Details

#_callbackObject

Returns the value of attribute _callback.



55
56
57
# File 'lib/ramaze/helper/user.rb', line 55

def _callback
  @_callback
end

#_modelObject

Returns the value of attribute _model.



55
56
57
# File 'lib/ramaze/helper/user.rb', line 55

def _model
  @_model
end

#_userObject

Returns the value of attribute _user.



55
56
57
# File 'lib/ramaze/helper/user.rb', line 55

def _user
  @_user
end

Instance Method Details

#_logged_in?Boolean

Returns:

  • (Boolean)


90
91
92
# File 'lib/ramaze/helper/user.rb', line 90

def _logged_in?
  !!_user
end

#_login(creds = _persistence) ⇒ Object



63
64
65
66
67
# File 'lib/ramaze/helper/user.rb', line 63

def (creds = _persistence)
  if @_user = _would_login?(creds)
    self._persistence = creds
  end
end

#_logoutObject



85
86
87
88
# File 'lib/ramaze/helper/user.rb', line 85

def _logout
  _persistence.clear
  STATE[:user] = nil
end

#_persistenceObject



98
99
100
# File 'lib/ramaze/helper/user.rb', line 98

def _persistence
  Current.session[:USER] || {}
end

#_persistence=(creds) ⇒ Object



94
95
96
# File 'lib/ramaze/helper/user.rb', line 94

def _persistence=(creds)
  Current.session[:USER] = creds
end

#_would_login?(creds) ⇒ Boolean

The callback should return an instance of the user, otherwise it should answer with nil.

This will not actually login, just check whether the credentials would result in a user.

Returns:

  • (Boolean)


74
75
76
77
78
79
80
81
82
83
# File 'lib/ramaze/helper/user.rb', line 74

def _would_login?(creds)
  if c = @_callback
    c.call(creds)
  elsif _model.respond_to?(:authenticate)
    _model.authenticate(creds)
  else
    Log.warn("Helper::User has no callback and there is no %p::authenticate" % _model)
    nil
  end
end