ruby on rails - Helper methods in Controller -
i have helper module:
module sessionshelper @current_user @current_session def current_user @current_user = user.find(cookies[:user_id]) if(cookies[:user_id]) end def current_session @current_session = session.find_by_secret_key(cookies[:session_secret_key]) end def current_user=(user) @current_user = user end def current_session=(session) @current_session = session end end
and controller:
class sessionscontroller < applicationcontroller include sessionshelper respond_to :json def create u = user.find_by_ip(request.remote_ip) u = user.create({:ip => request.remote_ip}) unless u s = session.create s.admin = u s.save! send(:current_user=,u) send(:current_session=,s) respond_with s end end
notice how have set current user :send
method, because calling current_user=u
directly in controller not it.
calling current_user
directly expected work, need use self
explicit receiver
def create u = user.find_by_ip(request.remote_ip) u = user.create({:ip => request.remote_ip}) unless u s = session.create s.admin = u s.save! self.current_user = u self.current_session = s respond_with s end
otherwise, following code set local method variable
def create u = user.find_by_ip(request.remote_ip) u = user.create({:ip => request.remote_ip}) unless u s = session.create s.admin = u s.save! current_user = u current_session = s respond_with s end
as side note, may want use meaningful variable names.
def create user = user.find_by_ip(request.remote_ip) || user.create(:ip => request.remote_ip) session = session.create session.admin = user session.save! self.current_user = user self.current_session = session respond_with session end
Comments
Post a Comment