aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRafael França <rafaelmfranca@gmail.com>2018-08-21 14:53:03 -0500
committerGitHub <noreply@github.com>2018-08-21 14:53:03 -0500
commitc03dde6117ed995d1ada57736b5b0d44dfe31ed5 (patch)
tree33e0e5e6cf087c31c96d91f9372b1a383c14387d
parent27934451b2f3f84770ac165e63a624fe075b0785 (diff)
parentec6089995d456c91aadf1cb2324b2e626016975c (diff)
downloadrails-c03dde6117ed995d1ada57736b5b0d44dfe31ed5.tar.gz
rails-c03dde6117ed995d1ada57736b5b0d44dfe31ed5.tar.bz2
rails-c03dde6117ed995d1ada57736b5b0d44dfe31ed5.zip
Merge pull request #29838 from fschwahn/patch-1
Add usage of procs without arguments to callbacks guide
-rw-r--r--activesupport/lib/active_support/callbacks.rb8
-rw-r--r--guides/source/active_record_callbacks.md8
2 files changed, 16 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index c266b432c0..487fe79f41 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -657,9 +657,17 @@ module ActiveSupport
# * <tt>:if</tt> - A symbol or an array of symbols, each naming an instance
# method or a proc; the callback will be called only when they all return
# a true value.
+ #
+ # If a proc is given, its body is evaluated in the context of the
+ # current object. It can also optionally accept the current object as
+ # an argument.
# * <tt>:unless</tt> - A symbol or an array of symbols, each naming an
# instance method or a proc; the callback will be called only when they
# all return a false value.
+ #
+ # If a proc is given, its body is evaluated in the context of the
+ # current object. It can also optionally accept the current object as
+ # an argument.
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
# existing chain rather than appended.
def set_callback(name, *filter_list, &block)
diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md
index 5b06ff78bb..5946acb412 100644
--- a/guides/source/active_record_callbacks.md
+++ b/guides/source/active_record_callbacks.md
@@ -319,6 +319,14 @@ class Order < ApplicationRecord
end
```
+As the proc is evaluated in the context of the object, it is also possible to write this as:
+
+```ruby
+class Order < ApplicationRecord
+ before_save :normalize_card_number, if: Proc.new { paid_with_card? }
+end
+```
+
### Multiple Conditions for Callbacks
When writing conditional callbacks, it is possible to mix both `:if` and `:unless` in the same callback declaration: