Ruby on Rails before_filter vs ruby's initialize

前端 未结 2 1318
忘了有多久
忘了有多久 2021-01-11 10:07

Just a thought in my mind. what is the difference the following

before_filter

class ApplicationController < ActionController::Bas         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-11 10:50

    For each request, you do get a fresh instance of ApplicationController, but the big no-no here is that you're attempting to override core behavior of ActionController::Base#initialize without calling the parent behavior.

    ApplicationController < ActionController::Base
    
      def initialize
        super # this calls ActionController::Base initialize
        init_foo
      end
    
      private
    
      def init_foo
        @foo = Foo.new
      end
    end
    

    This is not idiomatic Rails behavior though. They give you before_filter for a reason; so use it.

提交回复
热议问题