Reputation: 67
Hi i'm freshman to Ruby on Rails. I'm trying to make current_user method and i have a question. Many Rails courses make current_user method like this.
helper_method current_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
This method stores current user in instance variable. But in view file, most of course use method in view like this.
<% if current_user %>
...
<% end %>
I'm wondering why "store current user in instance variable" good right practice, even we will not use instance variable in view file. I'm still lacking in skills, so I have this question, so please take good care of me. Thanks.
Upvotes: 0
Views: 102
Reputation: 394
It's called memoization - a common practice used to speed up applications.
How it works: you are evaluating some expression just one time and cache value in memory to use any number of times further. You can find a lot information about it and I would recommend to check it, example:
https://www.honeybadger.io/blog/ruby-rails-memoization/
In your case
The first time you call current_user
method, instance variable @current_user
is nil
so you:
User.find(session[:user_id]) if session[:user_id]
);@current_user
.Next time you call current_user
you:
@current_user
(and authentication will not be proceeded).Current user
is something that will not be changed during the request. But if you wouldn't store user
in instance variable there would be a database request (step 1 - proceed authentication) every time you call current_user
method which is considered to be pretty time-expensive.
Upvotes: 2