简体   繁体   中英

rails practice for helper_method and instance variable (current_user)

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.

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:

  1. proceed authentication ( User.find(session[:user_id]) if session[:user_id] );
  2. save user in @current_user .

Next time you call current_user you:

  1. will get the value which is saved in @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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM