2017-08-27 27 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方法只是保留所有回调的列表,然后通过并找出什么是什么和做什么。

也许不是在回答中的深度,你所期望的,但希望这至少可以让你在正确的方向周围挖掘,并研究对自己的打算。