0

Sorry I couldn't phrase the question better. I'm following along the Rails Tutorial by Michael Hartl. It's an amazing book and I understood everything perfectly until this sign_in method

module SessionsHelper
  def sign_in(user)
    remember_token = User.new_remember_token
    cookies.permanent[:remember_token] = remember_token
    user.update_attribute(:remember_token, User.encrypt(remember_token))
    self.current_user = user
  end
......

The helper method is used in SessionsController

class SessionsController < ApplicationController
  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      sign_in user
      redirect_to user
    else
      flash.now[:error] = 'Invalid email/password combination'
      render 'new'
    end
  end
......

I know self evaluates to the current object and current_user is an attribute. But what is the current object here? Who called sign_in(user)?

otchkcom
  • 287
  • 6
  • 13

2 Answers2

0

In much earlier versions of Rails, the namespacing of the helpers determined which controllers views could use the helpers.

harsh4u
  • 2,550
  • 4
  • 24
  • 39
  • Could you be more specific? I tried to replace `sign_in user` with `SessionsController.new.sign_in user` but got the error `cookies.permanent[:remember_token] = remember_token` – otchkcom Jul 18 '13 at 05:21
  • @otchkcom the assumption here is that, if that book was old, which it isn't, the rails version used would include helpers in controllers with similar name. Not sure if this was intended as an answer or an insight. – rafb3 Dec 04 '14 at 01:36
0

The self in that controller method is the actual controller instance, which has access to it because that module was included in the class, basically extending its functionality with the methods declared within it which when called run inside the instance of the class just like a method defined inside the class. You can read more about these here.

If you are getting an error because that method doesn't exist on that class, then that's because you didn't include the module as shown in this answer to a similar question. (it's explained in the book).

Now, the reason why you get the error when accessing the controller directly as in this comment. is that you don't setup it properly as the rails router does, adding all the request information and other objects like the cookie jar.

If you want to know how it works, look on action pack dispatcher:

SessionController.action(:new).call(env)

That env comes from the request that the dispatcher receives from all the way back from rack, and basically is what you'd get from an HTTP request, a hash of strings with headers as keys and their values as values.

Community
  • 1
  • 1
rafb3
  • 1,694
  • 12
  • 12