How ActiveRecord implements `: if => ...` when validating

I looked at the ActiveRecord source to find out how :if => proc_or_method_name works with ActiveRecord checks, but the only instances :if in the source are in the comments explaining how the function should be called.

For example, you can have the following line in the model:

 validates_presence_of :name, :if => :nameable? 

and the check is only checked if the nameable? method nameable? returns the true value for this model.

Where is this functionality actually defined, since I cannot find this behavior anywhere in the source (Rails2)?

+4
source share
2 answers

Parameter :if marked in activesupport\lib\active_support\callbacks.rb file.

The should_run_callback method is should_run_callback to check whether the callback should be executed.

See also how the callback chain is handled, starting with the run_callbacks method in the same file.

Some code from v2.3.8 of this file:

 def should_run_callback?(*args) [options[:if]].flatten.compact.all? { |a| evaluate_method(a, *args) } && ![options[:unless]].flatten.compact.any? { |a| evaluate_method(a, *args) } end 

And here is how I found out (in case anyone is interested):

  • We downloaded Rails v2.3.8 from github and unzipped it.
  • grepp'ed for :if in all .rb files
  • activerecord/CHANGELOG posted a comment that mentioned:
    The if: option has been added for all checks that can use a block or method pointer to determine if the check should be performed or not. # 1324 [Dwayne Johnson / jhosteny].
  • Google'd for this comment. Found in google cache .
  • Found Comment / Addition was done on 05/21/05 10:57:18 by david
  • Positioned date 2005-05-21 on the history of github rails on page 546 :
  • Understood how it works :if
  • Found that the code that passed the link no longer exists in v2.3.8. should have found the last location of this code.
  • grepp'ed :if went again, although every file that was considered "good". came to activesupport/lib/active_support/callbacks.rb
  • searched for :if in the file and was found in only one place in the should_run_callback method.
  • Sent reply
  • Crossed fingers and waiting for generosity .: D

It was fun!

+3
source

Like Rails 3, ActiveRecord callbacks are defined in active_record / callbacks.rb , but since the ActiveRecord model is inherited from ActiveModel, you should also look in the active_model / callbacks.rb file.

The callback function itself is a separate component. In fact, the ActionController before / after filters is callbacks. For this reason, the callback system is a module defined in ActiveSupport :: Callbacks .

Combine all these 3 parts and you will get the ActiveRecord callback function.

+3
source

Source: https://habr.com/ru/post/1333028/


All Articles