I have been following this tutorial, online
http://ruby.railstutorial.org/chapters/sign-in-sign-out?version=3.2#top
and in part 8.2.3 there is something strange that I dont get. It says about this method:
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
current_user = user
end
end
and mentions that
current_user = user
is an assignment that has to be defined.This is strange cause in most languages i used so far when I want to assign a value I just use the "=" sign.
so he goes on defining this function:
def current_user=(user)
@current_user = user
end
why didn't he just use before?
module SessionsHelper
def sign_in(user)
cookies.permanent[:remember_token] = user.remember_token
@current_user = user
end
end
is the above approach wrong?
@current_user
is an instance variable. It is considered a good practice not to expose your naked instance variables to the whole world. Instead, you define getter and setter for it. In setter, for example, you can do validity checks. Or trigger callbacks. Or push/pop some state.
It's just plain more convenient, safe and flexible. At the cost of few lines of code.
Also, in ruby this is enforced at language level. You can't simply access instance variables.
class Foo
def initialize
@bar = 1
end
end
puts Foo.new.@bar # raises exception
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.