2012-09-22 27 views
1

ActiveSupport::Concernan article掛鉤。下面是Rails的一個工作實施:ActiveSupport :: Concern vs append_features

module ActionController 
    class Base < Metal 
    include AbstractController::Layouts 
    end 
end 

module AbstractController 
    module Layouts 
    extend ActiveSupport::Concern 

    include Rendering 

    included do 
     class_attribute :_layout, :_layout_conditions, :instance_accessor => false 
     self._layout = nil 
     self._layout_conditions = {} 
     _write_layout_method 
    end 

    module ClassMethods 
     ... 
    end 
    end 
end 

module AbstractController 
    module Rendering 
    extend ActiveSupport::Concern 

    included do 
     class_attribute :protected_instance_variables 
     self.protected_instance_variables = [] 
    end 

    module ClassMethods 
     ... 
    end 
    end 
end 

是如何extend呼叫Layoutsappend_features紅寶石掛鉤之前執行?必須先執行extend。畢竟,它的全部重點是劫持默認的append_features並重新實​​現它。但是,根據Ruby文檔,append_features在將此模塊(例如AbstractController::Layouts)包含在另一個模塊(例如ActionController::Base)中後立即執行。所以這裏對我來說很混亂。如果是這種情況,那麼ActiveSupport::Concern的覆蓋append_features將永遠不會被調用。

回答

1

這是我的看法:

你能想到的「包括」一樣,需要一個模塊作爲一個參數的方法;爲了包含模塊,模塊必須已經被環境加載;否則該行會失敗並出現常量錯誤。

因此,當調用include AbstractController::Layouts時,Layouts必須加載到AbstractController或頂級命名空間才能使用。

偷看動作包源代碼,事實證明,佈局自動加載,它確保它將在「include」行完成之前加載。

由於extend ActiveSupport::Concern當佈局是加載被執行時,append_features倍率將是由可用時間「包括」行的ActionController ::基地已完成執行。

之後,Layouts的append_features方法將以ActionController :: Base作爲參數執行。

相關問題