13

私がフォローしているチュートリアルのサブディレクトリapp/helpersには、多くのコントローラーとビューで使用される以下の SessionsHelper モジュールがあります。しかし、インスタンス変数は、current_user最初に作成されたときにどこに格納されるのでしょうか? 格納されているオブジェクトのクラスは何ですか?

current_userコントローラが最初にメソッドを呼び出すと、current_userインスタンス変数が作成されます。current_userビューがメソッドを呼び出すと、current_userインスタンス変数が既に存在するのはどうしてですか? selfビューのレンダリング中にコントローラー オブジェクトに設定されますか?

module SessionsHelper
  ...
  def current_user
    @current_user ||= User.find_by_remember_token(cookies[:remember_token])
  end
  ...
end
4

1 に答える 1

4

この回答は、コントローラーとビューの間でインスタンス変数がどのように渡されるかについて一般的に説明しています: How are Rails instance variables passed to views?

したがって、基本的に、 @current_user がコントローラーによって設定されている場合、そのインスタンス変数は (他のすべての変数と共に) コントローラー コンテキストからビュー コンテキストに渡されます。コントローラーによって設定されていない場合は、ビューが最初に使用するときに設定されます。

詳細については、他の回答を参照してください。よく読んでいます。

@mechanicalfishの回答から貼り付け:

def view_assigns
  hash = {}
  variables  = instance_variables
  variables -= protected_instance_variables
  variables -= DEFAULT_PROTECTED_INSTANCE_VARIABLES
  variables.each { |name| hash[name[1..-1]] = instance_variable_get(name) }
  hash
end

それらをビューに渡す (github):

def view_context
  view_context_class.new(view_renderer, view_assigns, self)
end

ビューでそれらを設定する (github):

def assign(new_assigns) # :nodoc:
  @_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) }
end
于 2015-07-25T13:42:41.500 に答える