Devise 如何让 current_user 对控制器和视图都可用?

How does Devise make current_user available to both controllers and views?

通过什么机制 Devise make the current_user method available to both controllers and views in Rails? I've looked at the source 但不知道他们是如何做到的。

通过使用 helper_method as you can see here: helpers.rb 和波纹管:

ActiveSupport.on_load(:action_controller) do
  helper_method "current_#{mapping}", "#{mapping}_signed_in?", "#{mapping}_session"
end

如果您按 current_user 搜索该文件,您将找不到任何内容,因为设计使用 mapping 占位符来允许您执行以下操作:

rails generate devise User # this will generate 3 helpers: current_user, user_signed_in? and user_session

rails generate devise Blogger # this will generate 3 helpers: current_blogger, blogge_signed_in? and blogger_session