2017-08-27 29 views
0

我已經完成了ActiveRecord回調的源代碼;我可以看到ActiveRecord的涉及一種用於像這樣的回調:ActiveRecord回調如何在Rails中實際工作

module Callbacks 
    extend ActiveSupport::Concern 

    CALLBACKS = [ 
     :after_initialize, :after_find, :after_touch, :before_validation, :after_validation, 
     :before_save, :around_save, :after_save, :before_create, :around_create, 
     :after_create, :before_update, :around_update, :after_update, 
     :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback 
    ] 

    def destroy #:nodoc: 
     @_destroy_callback_already_called ||= false 
     return if @_destroy_callback_already_called 
     @_destroy_callback_already_called = true 
     _run_destroy_callbacks { super } 
    rescue RecordNotDestroyed => e 
     @_association_destroy_exception = e 
     false 
    ensure 
     @_destroy_callback_already_called = false 
    end 

    def touch(*) #:nodoc: 
     _run_touch_callbacks { super } 
    end 

    private 

    def create_or_update(*) 
     _run_save_callbacks { super } 
    end 

    def _create_record 
     _run_create_callbacks { super } 
    end 

    def _update_record(*) 
     _run_update_callbacks { super } 
    end 
    end 
end 

現在我可以看到,通過符號的陣列的恆定可用回調。

進一步的調查顯示,回調函數中的create_or_update(*)方法涉及從persistance.rb文件(它對模型執行CRUD操作)中調用 - 並使用像這樣的行。

但是我不明白的是2個關鍵要素。

  1. 如何/哪裏的ActiveRecord確實會觸發回調,並在那裏是產生爲你傳遞給回調將要執行的方法的符號,它的方法。

  2. ActiveRecord如何知道回調甚至退出?也就是說,它是如何從一個類聲明發展到由ActiveRecord執行的?它被加載到某種寄存器中或者檢查每個負載的東西;等等?

+0

我認爲它可能在[ActiveRecord :: Callbacks.included](https://apidock.com/rails/v2.3.8/ActiveRecord/Callbacks/included/class)和[ActiveRecord :: Observer#define_callbacks]( https://apidock.com/rails/ActiveRecord/Observer/define_callbacks) –

回答

0

ActiveRecord和ActiveModel使用ActiveSupport::Callbacks來完成他們的骯髒工作。

如果你看看它的ClassMethods模塊,你會發現define_callbacks這是什麼定義(通過module_eval_run_update_callbacks和朋友。 _run_*_callbacks方法只是從主模塊中調用run_callbacks

因此,要回答你的問題:

  1. 我相信其實ActiveRecord的觸發你發佈的代碼的回調。看起來像ActiveRecord::Transactions有一對夫婦,它運行(交易相關的,足夠有趣)。

  2. 沒有挖得太深,看起來run_callbacks方法只是保留所有回調的列表,然後通過並找出什麼是什麼和做什麼。

也許不是在回答中的深度,你所期望的,但希望這至少可以讓你在正確的方向周圍挖掘,並研究對自己的打算。