This is just an OO question. Because the current_user=
is part of the session's contract with the world. It is promising that, no matter where the user is ultimately stored (such as in User.current_user
), you can always set it thru that interface.
Use of current_user setter in Ruby on Rails Tutorial by Michael Hartl?
-
23-09-2022 - |
Вопрос
I'm a little confused here. In chapter 8 of the fabulous Ruby on Rails Tutorial by Michael Hartl, I can't figure out why Michael uses a setter to set the instance variable @current_user
to user
.
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
def current_user=(user)
@current_user = user
end
end
Why did he not just skip the setter method and do it this way instead?
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))
@current_user = user
end
end
Is it just because it's best practice to implement a setter or I don't get something?
Решение
Другие советы
I haven't read it, but he could be
- Making a point
- Following best practice
- Intending to use the setter elsewhere, earlier or later in the tutorial
I am pretty sure he reuses that method later when the user loads another page. Something like:
# in application_controller
before_filter :authenticate
private
def authenticate
if cookies[:remember_token]
self.current_user = User.authenticate(cookies[:remember_token])
end
end
# in user.rb
def self.authenticate(token)
find_by_remember_token(User.encrypt(token))
end
Не связан с StackOverflow