SessionsHelper in railstutorial.org: Should helpers be general-purpose modules for code not needed in views?

前端 未结 4 1629
失恋的感觉
失恋的感觉 2020-12-14 19:13

railstutorial.org has a suggestion which strikes me as a little odd.

It suggests this code:

class ApplicationController < ActionController::Base         


        
4条回答
  •  猫巷女王i
    2020-12-14 19:51

    Indeed, your feeling is correct.

    I would implement this the other way around: add the functions sign_in and current_user to ApplicationController (or if you really want to: in a separate module defined in lib and include it), and then make sure that the current_user method is available in the view.

    In short:

    class ApplicationController
    
      helper_method :current_user
    
      def sign_in
    
      end
    
      def current_user
        @current_user ||= user_from_remember_token
      end
    end
    

    Of course, if you have a lot of code to place into your ApplicationController it can get messy. In that case I would create a file lib\session_management.rb:

    module SessionManagement
      def self.included(base)
        base.helper_method :current_user
      end
    
      def sign_in
        ..
      end
    
      def current_user
        ..
      end
    end
    

    and inside your controller you can then just write:

    class ApplicationController
      include SessionManagement
    end
    

提交回复
热议问题