rails 使用实例变量进行记忆

memoization in rails using an instance variable

我正在关注 Michael Hartl 的 railstutorial。在chapter 8.2.2中他定义了一个变量@current_user和一个方法current_user.

app/helpers/sessions_helper.rb 看起来像这样:

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Returns the current logged-in user (if any).
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

end

Hartl 定义了@current_user 一个实例变量(我猜是 User 对象);如果 @current_user 本身就是 User class 的一个实例,那么它怎么可能是一个实例变量呢?

SessionsHelper 模块混合到您的控制器中,因此 @current_user 将被设置为处理当前请求的控制器的实例变量(Rails 创建一个新控制器处理每个请求的实例)

这是一个很好的问题。似乎这种安排不是计划好的,它只是发生了:你需要有一个在方法(范围)之外具有某种内存的变量,以便比较 @current_user=@ current_user,但同时整个安排在理论上毫无意义。

本文写于 2008 年,由 rails 核心团队成员校对。这段很能说明情况:

http://www.railway.at/articles/2008/09/20/a-guide-to-memoization/

--> "A little note on naming here: Some people seem to prefer prefixing the memoizing variable’s name with an underscore to indicate that it’s not meant to be used as an actual instance variable. To be honest, I don’t think this is really necessary unless you define a whole bunch of instance variables and memoized variables."