1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activesupport/lib/active_support/callbacks.rb

821 lines
26 KiB
Ruby
Raw Normal View History

require 'active_support/concern'
require 'active_support/descendants_tracker'
require 'active_support/core_ext/array/extract_options'
require 'active_support/core_ext/class/attribute'
require 'active_support/core_ext/kernel/reporting'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/string/filters'
2013-05-14 19:18:11 -04:00
require 'thread'
module ActiveSupport
# Callbacks are code hooks that are run at key points in an object's life cycle.
2012-09-17 01:22:18 -04:00
# The typical use case is to have a base class define a set of callbacks
# relevant to the other functionality it supplies, so that subclasses can
# install callbacks that enhance or modify the base functionality without
# needing to override or redefine methods of the base class.
#
2012-09-17 01:22:18 -04:00
# Mixing in this module allows you to define the events in the object's
# life cycle that will support callbacks (via +ClassMethods.define_callbacks+),
2012-09-17 01:22:18 -04:00
# set the instance methods, procs, or callback objects to be called (via
# +ClassMethods.set_callback+), and run the installed callbacks at the
2012-09-17 01:22:18 -04:00
# appropriate times (via +run_callbacks+).
#
2012-09-17 01:22:18 -04:00
# Three kinds of callbacks are supported: before callbacks, run before a
# certain event; after callbacks, run after the event; and around callbacks,
# blocks that surround the event, triggering it when they yield. Callback code
# can be contained in instance methods, procs or lambdas, or callback objects
# that respond to certain predetermined methods. See +ClassMethods.set_callback+
# for details.
#
2011-01-09 13:00:15 -05:00
# class Record
# include ActiveSupport::Callbacks
# define_callbacks :save
#
# def save
# run_callbacks :save do
# puts "- save"
# end
# end
# end
#
2011-01-09 13:00:15 -05:00
# class PersonRecord < Record
# set_callback :save, :before, :saving_message
# def saving_message
# puts "saving..."
# end
#
# set_callback :save, :after do |object|
# puts "saved"
# end
# end
#
2011-01-09 13:00:15 -05:00
# person = PersonRecord.new
# person.save
#
# Output:
# saving...
# - save
# saved
module Callbacks
extend Concern
included do
extend ActiveSupport::DescendantsTracker
end
2013-04-21 23:27:27 -04:00
CALLBACK_FILTER_TYPES = [:before, :after, :around]
2011-01-09 13:00:15 -05:00
# Runs the callbacks for the given event.
#
# Calls the before and around callbacks in the order they were set, yields
2012-09-17 01:22:18 -04:00
# the block (if given one), and then runs the after callbacks in reverse
# order.
2011-01-09 13:00:15 -05:00
#
2012-09-17 01:22:18 -04:00
# If the callback chain was halted, returns +false+. Otherwise returns the
2014-06-29 14:14:40 -04:00
# result of the block, +nil+ if no callbacks have been set, or +true+
# if callbacks have been set but no block is given.
2011-01-09 13:00:15 -05:00
#
# run_callbacks :save do
# save
# end
def run_callbacks(kind, &block)
send "_run_#{kind}_callbacks", &block
Reduce allocations when running AR callbacks. Inspired by @tenderlove's work in c363fff29f060e6a2effe1e4bb2c4dd4cd805d6e, this reduces the number of strings allocated when running callbacks for ActiveRecord instances. I measured that using this script: ``` require 'objspace' require 'active_record' require 'allocation_tracer' ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" ActiveRecord::Base.connection.instance_eval do create_table(:articles) { |t| t.string :name } end class Article < ActiveRecord::Base; end a = Article.create name: "foo" a = Article.find a.id N = 10 result = ObjectSpace::AllocationTracer.trace do N.times { Article.find a.id } end result.sort.each do |k,v| p k => v end puts "total: #{result.values.map(&:first).inject(:+)}" ``` When I run this against master and this branch I get this output: ``` pete@balloon:~/projects/rails/activerecord$ git checkout master M Gemfile Switched to branch 'master' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_before pete@balloon:~/projects/rails/activerecord$ git checkout remove-dynamic-send-on-built-in-callbacks M Gemfile Switched to branch 'remove-dynamic-send-on-built-in-callbacks' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_after pete@balloon:~/projects/rails/activerecord$ diff allocations_before allocations_after 39d38 < {["/home/pete/projects/rails/activesupport/lib/active_support/callbacks.rb", 81]=>[40, 0, 0, 0, 0, 0]} 42c41 < total: 630 --- > total: 590 ``` In addition to this, there are two micro-optimizations present: * Using `block.call if block` vs `yield if block_given?` when the block was being captured already. ``` pete@balloon:~/projects$ cat benchmark_block_call_vs_yield.rb require 'benchmark/ips' def block_capture_with_yield &block yield if block_given? end def block_capture_with_call &block block.call if block end def no_block_capture yield if block_given? end Benchmark.ips do |b| b.report("block_capture_with_yield") { block_capture_with_yield } b.report("block_capture_with_call") { block_capture_with_call } b.report("no_block_capture") { no_block_capture } end pete@balloon:~/projects$ ruby benchmark_block_call_vs_yield.rb Calculating ------------------------------------- block_capture_with_yield 124979 i/100ms block_capture_with_call 138340 i/100ms no_block_capture 136827 i/100ms ------------------------------------------------- block_capture_with_yield 5703108.9 (±2.4%) i/s - 28495212 in 4.999368s block_capture_with_call 6840730.5 (±3.6%) i/s - 34169980 in 5.002649s no_block_capture 5821141.4 (±2.8%) i/s - 29144151 in 5.010580s ``` * Defining and calling methods instead of using send. ``` pete@balloon:~/projects$ cat benchmark_method_call_vs_send.rb require 'benchmark/ips' class Foo def tacos nil end end my_foo = Foo.new Benchmark.ips do |b| b.report('send') { my_foo.send('tacos') } b.report('call') { my_foo.tacos } end pete@balloon:~/projects$ ruby benchmark_method_call_vs_send.rb Calculating ------------------------------------- send 97736 i/100ms call 151142 i/100ms ------------------------------------------------- send 2683730.3 (±2.8%) i/s - 13487568 in 5.029763s call 8005963.9 (±2.7%) i/s - 40052630 in 5.006604s ``` The result of this is making typical ActiveRecord operations slightly faster: https://gist.github.com/phiggins/e46e51dcc7edb45b5f98
2014-09-28 17:42:26 -04:00
end
private
def _run_callbacks(callbacks, &block)
if callbacks.empty?
block.call if block
else
Reduce allocations when running AR callbacks. Inspired by @tenderlove's work in c363fff29f060e6a2effe1e4bb2c4dd4cd805d6e, this reduces the number of strings allocated when running callbacks for ActiveRecord instances. I measured that using this script: ``` require 'objspace' require 'active_record' require 'allocation_tracer' ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" ActiveRecord::Base.connection.instance_eval do create_table(:articles) { |t| t.string :name } end class Article < ActiveRecord::Base; end a = Article.create name: "foo" a = Article.find a.id N = 10 result = ObjectSpace::AllocationTracer.trace do N.times { Article.find a.id } end result.sort.each do |k,v| p k => v end puts "total: #{result.values.map(&:first).inject(:+)}" ``` When I run this against master and this branch I get this output: ``` pete@balloon:~/projects/rails/activerecord$ git checkout master M Gemfile Switched to branch 'master' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_before pete@balloon:~/projects/rails/activerecord$ git checkout remove-dynamic-send-on-built-in-callbacks M Gemfile Switched to branch 'remove-dynamic-send-on-built-in-callbacks' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_after pete@balloon:~/projects/rails/activerecord$ diff allocations_before allocations_after 39d38 < {["/home/pete/projects/rails/activesupport/lib/active_support/callbacks.rb", 81]=>[40, 0, 0, 0, 0, 0]} 42c41 < total: 630 --- > total: 590 ``` In addition to this, there are two micro-optimizations present: * Using `block.call if block` vs `yield if block_given?` when the block was being captured already. ``` pete@balloon:~/projects$ cat benchmark_block_call_vs_yield.rb require 'benchmark/ips' def block_capture_with_yield &block yield if block_given? end def block_capture_with_call &block block.call if block end def no_block_capture yield if block_given? end Benchmark.ips do |b| b.report("block_capture_with_yield") { block_capture_with_yield } b.report("block_capture_with_call") { block_capture_with_call } b.report("no_block_capture") { no_block_capture } end pete@balloon:~/projects$ ruby benchmark_block_call_vs_yield.rb Calculating ------------------------------------- block_capture_with_yield 124979 i/100ms block_capture_with_call 138340 i/100ms no_block_capture 136827 i/100ms ------------------------------------------------- block_capture_with_yield 5703108.9 (±2.4%) i/s - 28495212 in 4.999368s block_capture_with_call 6840730.5 (±3.6%) i/s - 34169980 in 5.002649s no_block_capture 5821141.4 (±2.8%) i/s - 29144151 in 5.010580s ``` * Defining and calling methods instead of using send. ``` pete@balloon:~/projects$ cat benchmark_method_call_vs_send.rb require 'benchmark/ips' class Foo def tacos nil end end my_foo = Foo.new Benchmark.ips do |b| b.report('send') { my_foo.send('tacos') } b.report('call') { my_foo.tacos } end pete@balloon:~/projects$ ruby benchmark_method_call_vs_send.rb Calculating ------------------------------------- send 97736 i/100ms call 151142 i/100ms ------------------------------------------------- send 2683730.3 (±2.8%) i/s - 13487568 in 5.029763s call 8005963.9 (±2.7%) i/s - 40052630 in 5.006604s ``` The result of this is making typical ActiveRecord operations slightly faster: https://gist.github.com/phiggins/e46e51dcc7edb45b5f98
2014-09-28 17:42:26 -04:00
runner = callbacks.compile
e = Filters::Environment.new(self, false, nil, block)
runner.call(e).value
end
end
2013-12-12 00:59:23 -05:00
# A hook invoked every time a before callback is halted.
2012-07-26 14:44:36 -04:00
# This can be overridden in AS::Callback implementors in order
# to provide better debugging/logging.
def halted_callback_hook(filter)
end
module Conditionals # :nodoc:
class Value
def initialize(&block)
@block = block
end
def call(target, value); @block.call(value); end
end
end
module Filters
Environment = Struct.new(:target, :halted, :value, :run_block)
2013-05-13 19:59:05 -04:00
class End
def call(env)
block = env.run_block
env.value = !env.halted && (!block || block.call)
env
end
end
ENDING = End.new
2013-05-14 14:20:34 -04:00
class Before
def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter)
2013-05-14 19:03:09 -04:00
halted_lambda = chain_config[:terminator]
2013-05-14 14:20:34 -04:00
if chain_config.key?(:terminator) && user_conditions.any?
halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
2013-05-14 14:20:34 -04:00
elsif chain_config.key? :terminator
halting(callback_sequence, user_callback, halted_lambda, filter)
2013-05-14 14:20:34 -04:00
elsif user_conditions.any?
conditional(callback_sequence, user_callback, user_conditions)
2013-05-14 14:20:34 -04:00
else
simple callback_sequence, user_callback
2013-05-14 14:20:34 -04:00
end
end
def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter)
callback_sequence.before do |env|
target = env.target
value = env.value
halted = env.halted
if !halted && user_conditions.all? { |c| c.call(target, value) }
result_lambda = -> { user_callback.call target, value }
env.halted = halted_lambda.call(target, result_lambda)
if env.halted
target.send :halted_callback_hook, filter
end
end
env
end
end
private_class_method :halting_and_conditional
def self.halting(callback_sequence, user_callback, halted_lambda, filter)
callback_sequence.before do |env|
target = env.target
value = env.value
halted = env.halted
2013-05-15 12:18:08 -04:00
unless halted
result_lambda = -> { user_callback.call target, value }
env.halted = halted_lambda.call(target, result_lambda)
if env.halted
target.send :halted_callback_hook, filter
end
end
env
end
end
private_class_method :halting
def self.conditional(callback_sequence, user_callback, user_conditions)
callback_sequence.before do |env|
target = env.target
value = env.value
if user_conditions.all? { |c| c.call(target, value) }
user_callback.call target, value
end
env
end
end
private_class_method :conditional
def self.simple(callback_sequence, user_callback)
callback_sequence.before do |env|
user_callback.call env.target, env.value
env
end
end
private_class_method :simple
2013-05-14 14:20:34 -04:00
end
2013-05-14 14:37:34 -04:00
class After
def self.build(callback_sequence, user_callback, user_conditions, chain_config)
2013-05-14 14:37:34 -04:00
if chain_config[:skip_after_callbacks_if_terminated]
if chain_config.key?(:terminator) && user_conditions.any?
halting_and_conditional(callback_sequence, user_callback, user_conditions)
2013-05-14 14:37:34 -04:00
elsif chain_config.key?(:terminator)
halting(callback_sequence, user_callback)
2013-05-14 14:37:34 -04:00
elsif user_conditions.any?
conditional callback_sequence, user_callback, user_conditions
2013-05-14 14:37:34 -04:00
else
simple callback_sequence, user_callback
2013-05-14 14:37:34 -04:00
end
else
if user_conditions.any?
conditional callback_sequence, user_callback, user_conditions
2013-05-14 14:37:34 -04:00
else
simple callback_sequence, user_callback
2013-05-14 14:37:34 -04:00
end
end
end
def self.halting_and_conditional(callback_sequence, user_callback, user_conditions)
callback_sequence.after do |env|
2013-05-14 14:37:34 -04:00
target = env.target
value = env.value
halted = env.halted
if !halted && user_conditions.all? { |c| c.call(target, value) }
user_callback.call target, value
end
2013-05-14 14:37:34 -04:00
env
end
2013-05-14 14:37:34 -04:00
end
private_class_method :halting_and_conditional
2013-05-14 14:37:34 -04:00
def self.halting(callback_sequence, user_callback)
callback_sequence.after do |env|
2013-05-15 12:18:08 -04:00
unless env.halted
2013-05-14 14:37:34 -04:00
user_callback.call env.target, env.value
end
2013-05-14 14:37:34 -04:00
env
end
2013-05-14 14:37:34 -04:00
end
private_class_method :halting
2013-05-14 14:37:34 -04:00
def self.conditional(callback_sequence, user_callback, user_conditions)
callback_sequence.after do |env|
2013-05-14 14:37:34 -04:00
target = env.target
value = env.value
if user_conditions.all? { |c| c.call(target, value) }
user_callback.call target, value
end
2013-05-14 14:37:34 -04:00
env
end
2013-05-14 14:37:34 -04:00
end
private_class_method :conditional
2013-05-14 14:37:34 -04:00
def self.simple(callback_sequence, user_callback)
callback_sequence.after do |env|
2013-05-14 14:37:34 -04:00
user_callback.call env.target, env.value
2013-05-14 14:37:34 -04:00
env
end
2013-05-14 14:37:34 -04:00
end
private_class_method :simple
2013-05-14 14:37:34 -04:00
end
2013-05-14 14:48:04 -04:00
class Around
def self.build(callback_sequence, user_callback, user_conditions, chain_config)
2013-05-14 14:48:04 -04:00
if chain_config.key?(:terminator) && user_conditions.any?
halting_and_conditional(callback_sequence, user_callback, user_conditions)
2013-05-14 14:48:04 -04:00
elsif chain_config.key? :terminator
halting(callback_sequence, user_callback)
2013-05-14 14:48:04 -04:00
elsif user_conditions.any?
conditional(callback_sequence, user_callback, user_conditions)
2013-05-14 14:48:04 -04:00
else
simple(callback_sequence, user_callback)
2013-05-14 14:48:04 -04:00
end
end
def self.halting_and_conditional(callback_sequence, user_callback, user_conditions)
callback_sequence.around do |env, &run|
2013-05-14 14:48:04 -04:00
target = env.target
value = env.value
halted = env.halted
if !halted && user_conditions.all? { |c| c.call(target, value) }
user_callback.call(target, value) {
run.call.value
2013-05-14 14:48:04 -04:00
}
env
else
run.call
2013-05-14 14:48:04 -04:00
end
end
2013-05-14 14:48:04 -04:00
end
private_class_method :halting_and_conditional
2013-05-14 14:48:04 -04:00
def self.halting(callback_sequence, user_callback)
callback_sequence.around do |env, &run|
2013-05-14 14:48:04 -04:00
target = env.target
value = env.value
if env.halted
run.call
else
2013-05-14 14:48:04 -04:00
user_callback.call(target, value) {
run.call.value
2013-05-14 14:48:04 -04:00
}
env
end
end
2013-05-14 14:48:04 -04:00
end
private_class_method :halting
2013-05-14 14:48:04 -04:00
def self.conditional(callback_sequence, user_callback, user_conditions)
callback_sequence.around do |env, &run|
2013-05-14 14:48:04 -04:00
target = env.target
value = env.value
if user_conditions.all? { |c| c.call(target, value) }
user_callback.call(target, value) {
run.call.value
2013-05-14 14:48:04 -04:00
}
env
else
run.call
2013-05-14 14:48:04 -04:00
end
end
2013-05-14 14:48:04 -04:00
end
private_class_method :conditional
2013-05-14 14:48:04 -04:00
def self.simple(callback_sequence, user_callback)
callback_sequence.around do |env, &run|
2013-05-14 14:48:04 -04:00
user_callback.call(env.target, env.value) {
run.call.value
2013-05-14 14:48:04 -04:00
}
env
end
2013-05-14 14:48:04 -04:00
end
private_class_method :simple
2013-05-14 14:48:04 -04:00
end
end
2011-01-09 13:00:15 -05:00
class Callback #:nodoc:#
2013-05-10 14:55:27 -04:00
def self.build(chain, filter, kind, options)
new chain.name, filter, kind, options, chain.config
2013-05-07 16:26:23 -04:00
end
attr_accessor :kind, :name
attr_reader :chain_config
def initialize(name, filter, kind, options, chain_config)
@chain_config = chain_config
@name = name
2013-05-10 14:50:50 -04:00
@kind = kind
@filter = filter
@key = compute_identifier filter
@if = Array(options[:if])
@unless = Array(options[:unless])
end
2013-05-10 14:50:50 -04:00
def filter; @key; end
def raw_filter; @filter; end
2013-05-08 16:36:04 -04:00
def merge_conditional_options(chain, if_option:, unless_option:)
2013-05-15 12:43:17 -04:00
options = {
:if => @if.dup,
:unless => @unless.dup
2013-05-10 15:00:35 -04:00
}
2013-05-10 17:12:56 -04:00
options[:if].concat Array(unless_option)
options[:unless].concat Array(if_option)
2013-05-10 17:12:56 -04:00
2013-05-15 12:43:17 -04:00
self.class.build chain, @filter, @kind, options
end
def matches?(_kind, _filter)
2013-05-08 15:01:55 -04:00
@kind == _kind && filter == _filter
end
def duplicates?(other)
2013-05-10 14:50:50 -04:00
case @filter
2013-05-10 14:45:48 -04:00
when Symbol, String
matches?(other.kind, other.filter)
else
false
end
end
# Wraps code with filter
def apply(callback_sequence)
2013-05-09 17:55:15 -04:00
user_conditions = conditions_lambdas
2013-05-10 14:50:50 -04:00
user_callback = make_lambda @filter
2013-05-09 14:58:55 -04:00
2013-05-10 14:50:50 -04:00
case kind
when :before
Filters::Before.build(callback_sequence, user_callback, user_conditions, chain_config, @filter)
when :after
Filters::After.build(callback_sequence, user_callback, user_conditions, chain_config)
when :around
Filters::Around.build(callback_sequence, user_callback, user_conditions, chain_config)
end
end
private
2013-05-08 20:57:06 -04:00
def invert_lambda(l)
lambda { |*args, &blk| !l.call(*args, &blk) }
end
2013-05-09 14:58:55 -04:00
# Filters support:
#
# Symbols:: A method to call.
# Strings:: Some content to evaluate.
# Procs:: A proc to call with the object.
# Objects:: An object with a <tt>before_foo</tt> method on it to call.
#
# All of these objects are converted into a lambda and handled
# the same after this point.
2013-05-08 20:57:06 -04:00
def make_lambda(filter)
case filter
when Symbol
lambda { |target, _, &blk| target.send filter, &blk }
2013-05-08 20:57:06 -04:00
when String
l = eval "lambda { |value| #{filter} }"
lambda { |target, value| target.instance_exec(value, &l) }
when Conditionals::Value then filter
2013-05-08 20:57:06 -04:00
when ::Proc
2013-05-14 17:02:33 -04:00
if filter.arity > 1
return lambda { |target, _, &block|
raise ArgumentError unless block
target.instance_exec(target, block, &filter)
}
end
2013-05-08 20:57:06 -04:00
if filter.arity <= 0
lambda { |target, _| target.instance_exec(&filter) }
2013-05-08 20:57:06 -04:00
else
lambda { |target, _| target.instance_exec(target, &filter) }
2013-05-08 20:57:06 -04:00
end
else
scopes = Array(chain_config[:scope])
2013-05-08 20:57:06 -04:00
method_to_call = scopes.map{ |s| public_send(s) }.join("_")
lambda { |target, _, &blk|
filter.public_send method_to_call, target, &blk
}
end
end
2013-05-08 16:36:04 -04:00
def compute_identifier(filter)
case filter
when String, ::Proc
filter.object_id
else
filter
end
end
2013-05-09 14:58:55 -04:00
def conditions_lambdas
@if.map { |c| make_lambda c } +
@unless.map { |c| invert_lambda make_lambda c }
end
end
# Execute before and after filters in a sequence instead of
# chaining them with nested lambda calls, see:
# https://github.com/rails/rails/issues/18011
class CallbackSequence
def initialize(&call)
@call = call
@before = []
@after = []
end
def before(&before)
@before.unshift(before)
self
end
def after(&after)
@after.push(after)
self
end
def around(&around)
CallbackSequence.new do |arg|
around.call(arg) {
self.call(arg)
}
end
end
def call(arg)
@before.each { |b| b.call(arg) }
value = @call.call(arg)
@after.each { |a| a.call(arg) }
value
end
end
2012-09-17 01:22:18 -04:00
# An Array with a compile method.
class CallbackChain #:nodoc:#
include Enumerable
attr_reader :name, :config
# If true, any callback returning +false+ will halt the entire callback
# chain and display a deprecation message. If false, callback chains will
# only be halted by calling +throw :abort+. Defaults to +true+.
class_attribute :halt_and_display_warning_on_return_false
self.halt_and_display_warning_on_return_false = true
def initialize(name, config)
@name = name
@config = {
scope: [:kind],
terminator: default_terminator
2013-03-29 11:28:46 -04:00
}.merge!(config)
@chain = []
2013-05-10 14:00:25 -04:00
@callbacks = nil
2013-05-14 19:18:11 -04:00
@mutex = Mutex.new
end
2013-05-14 15:03:33 -04:00
def each(&block); @chain.each(&block); end
def index(o); @chain.index(o); end
def empty?; @chain.empty?; end
2013-05-10 14:00:25 -04:00
def insert(index, o)
@callbacks = nil
@chain.insert(index, o)
end
def delete(o)
@callbacks = nil
@chain.delete(o)
end
def clear
@callbacks = nil
@chain.clear
self
end
def initialize_copy(other)
2013-05-10 14:00:25 -04:00
@callbacks = nil
@chain = other.chain.dup
2013-05-14 19:18:11 -04:00
@mutex = Mutex.new
end
2012-02-05 05:58:44 -05:00
def compile
2013-05-14 19:18:11 -04:00
@callbacks || @mutex.synchronize do
final_sequence = CallbackSequence.new { |env| Filters::ENDING.call(env) }
@callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback|
callback.apply callback_sequence
2013-05-14 19:18:11 -04:00
end
end
end
def append(*callbacks)
callbacks.each { |c| append_one(c) }
end
def prepend(*callbacks)
callbacks.each { |c| prepend_one(c) }
end
protected
def chain; @chain; end
private
def append_one(callback)
2013-05-10 14:00:25 -04:00
@callbacks = nil
remove_duplicates(callback)
@chain.push(callback)
end
def prepend_one(callback)
2013-05-10 14:00:25 -04:00
@callbacks = nil
remove_duplicates(callback)
@chain.unshift(callback)
end
def remove_duplicates(callback)
2013-05-10 14:00:25 -04:00
@callbacks = nil
@chain.delete_if { |c| callback.duplicates?(c) }
end
def default_terminator
Proc.new do |target, result_lambda|
terminate = true
catch(:abort) do
result = result_lambda.call if result_lambda.is_a?(Proc)
if halt_and_display_warning_on_return_false && result == false
display_deprecation_warning_for_false_terminator
else
terminate = false
end
end
terminate
end
end
def display_deprecation_warning_for_false_terminator
ActiveSupport::Deprecation.warn(<<-MSG.squish)
Returning `false` in a callback will not implicitly halt a callback chain in the next release of Rails.
To explicitly halt a callback chain, please use `throw :abort` instead.
MSG
end
end
module ClassMethods
def normalize_callback_params(filters, block) # :nodoc:
2013-04-21 23:27:27 -04:00
type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before
options = filters.extract_options!
filters.unshift(block) if block
[type, filters, options.dup]
2013-05-13 17:11:09 -04:00
end
2013-05-13 17:11:09 -04:00
# This is used internally to append, prepend and skip callbacks to the
# CallbackChain.
def __update_callbacks(name) #:nodoc:
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target|
chain = target.get_callbacks name
yield target, chain.dup
end
end
2011-01-09 13:00:15 -05:00
# Install a callback for the given event.
#
# set_callback :save, :before, :before_meth
2012-09-17 01:22:18 -04:00
# set_callback :save, :after, :after_meth, if: :condition
# set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff }
#
2011-01-09 13:00:15 -05:00
# The second arguments indicates whether the callback is to be run +:before+,
# +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This
# means the first example above can also be written as:
#
# set_callback :save, :before_meth
#
# The callback can be specified as a symbol naming an instance method; as a
# proc, lambda, or block; as a string to be instance evaluated; or as an
2012-09-17 01:22:18 -04:00
# object that responds to a certain method determined by the <tt>:scope</tt>
# argument to +define_callbacks+.
2011-01-09 13:00:15 -05:00
#
# If a proc, lambda, or block is given, its body is evaluated in the context
# of the current object. It can also optionally accept the current object as
# an argument.
#
2012-09-17 01:22:18 -04:00
# Before and around callbacks are called in the order that they are set;
# after callbacks are called in the reverse order.
#
# Around callbacks can access the return value from the event, if it
# wasn't halted, from the +yield+ call.
2011-01-09 13:00:15 -05:00
#
# ===== Options
#
2012-09-17 01:22:18 -04:00
# * <tt>:if</tt> - A symbol naming an instance method or a proc; the
# callback will be called only when it returns a +true+ value.
# * <tt>:unless</tt> - A symbol naming an instance method or a proc; the
# callback will be called only when it returns a +false+ value.
# * <tt>:prepend</tt> - If +true+, the callback will be prepended to the
# existing chain rather than appended.
def set_callback(name, *filter_list, &block)
type, filters, options = normalize_callback_params(filter_list, block)
2013-05-14 15:03:33 -04:00
self_chain = get_callbacks name
mapped = filters.map do |filter|
Callback.build(self_chain, filter, type, options)
end
__update_callbacks(name) do |target, chain|
options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped)
target.set_callbacks name, chain
end
end
2012-09-17 01:22:18 -04:00
# Skip a previously set callback. Like +set_callback+, <tt>:if</tt> or
# <tt>:unless</tt> options may be passed in order to control when the
# callback is skipped.
#
# class Writer < Person
2012-09-17 01:22:18 -04:00
# skip_callback :validate, :before, :check_membership, if: -> { self.age > 18 }
# end
def skip_callback(name, *filter_list, &block)
type, filters, options = normalize_callback_params(filter_list, block)
__update_callbacks(name) do |target, chain|
filters.each do |filter|
filter = chain.find {|c| c.matches?(type, filter) }
if filter && options.any?
new_filter = filter.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless])
chain.insert(chain.index(filter), new_filter)
end
chain.delete(filter)
end
target.set_callbacks name, chain
end
end
2011-01-09 13:00:15 -05:00
# Remove all set callbacks for the given event.
def reset_callbacks(name)
callbacks = get_callbacks name
ActiveSupport::DescendantsTracker.descendants(self).each do |target|
chain = target.get_callbacks(name).dup
callbacks.each { |c| chain.delete(c) }
target.set_callbacks name, chain
end
self.set_callbacks name, callbacks.dup.clear
end
# Define sets of events in the object life cycle that support callbacks.
#
# define_callbacks :validate
2011-01-09 13:00:15 -05:00
# define_callbacks :initialize, :save, :destroy
#
2011-01-09 13:00:15 -05:00
# ===== Options
#
2012-09-17 01:22:18 -04:00
# * <tt>:terminator</tt> - Determines when a before filter will halt the
# callback chain, preventing following before and around callbacks from
# being called and the event from being triggered.
# This should be a lambda to be executed.
# The current object and the return result of the callback will be called
# with the lambda.
#
# define_callbacks :validate, terminator: ->(target, result) { result == false }
#
2011-01-09 13:00:15 -05:00
# In this example, if any before validate callbacks returns +false+,
# any successive before and around callback is not executed.
# Defaults to +false+, meaning no value halts the chain.
#
2012-09-17 01:22:18 -04:00
# * <tt>:skip_after_callbacks_if_terminated</tt> - Determines if after
# callbacks should be terminated by the <tt>:terminator</tt> option. By
# default after callbacks are executed no matter if callback chain was
# terminated or not. This option makes sense only when <tt>:terminator</tt>
2012-09-17 01:22:18 -04:00
# option is specified.
#
2012-09-17 01:22:18 -04:00
# * <tt>:scope</tt> - Indicates which methods should be executed when an
# object is used as a callback.
#
2011-01-09 13:00:15 -05:00
# class Audit
# def before(caller)
# puts 'Audit: before is called'
# end
2010-06-14 16:52:47 -04:00
#
2011-01-09 13:00:15 -05:00
# def before_save(caller)
# puts 'Audit: before_save is called'
# end
# end
#
2011-01-09 13:00:15 -05:00
# class Account
# include ActiveSupport::Callbacks
2010-06-14 16:52:47 -04:00
#
2011-01-09 13:00:15 -05:00
# define_callbacks :save
# set_callback :save, :before, Audit.new
2010-06-14 16:52:47 -04:00
#
2011-01-09 13:00:15 -05:00
# def save
# run_callbacks :save do
# puts 'save in main'
# end
# end
# end
#
2012-09-17 01:22:18 -04:00
# In the above case whenever you save an account the method
# <tt>Audit#before</tt> will be called. On the other hand
#
2012-09-17 01:22:18 -04:00
# define_callbacks :save, scope: [:kind, :name]
#
2012-09-17 01:22:18 -04:00
# would trigger <tt>Audit#before_save</tt> instead. That's constructed
# by calling <tt>#{kind}_#{name}</tt> on the given instance. In this
# case "kind" is "before" and "name" is "save". In this context +:kind+
# and +:name+ have special meanings: +:kind+ refers to the kind of
# callback (before/after/around) and +:name+ refers to the method on
# which callbacks are being defined.
#
2011-01-09 13:00:15 -05:00
# A declaration like
#
2012-09-17 01:22:18 -04:00
# define_callbacks :save, scope: [:name]
#
2011-01-09 13:00:15 -05:00
# would call <tt>Audit#save</tt>.
#
# NOTE: +method_name+ passed to `define_model_callbacks` must not end with
# `!`, `?` or `=`.
def define_callbacks(*names)
options = names.extract_options!
2013-05-14 19:03:09 -04:00
names.each do |name|
class_attribute "_#{name}_callbacks"
set_callbacks name, CallbackChain.new(name, options)
Reduce allocations when running AR callbacks. Inspired by @tenderlove's work in c363fff29f060e6a2effe1e4bb2c4dd4cd805d6e, this reduces the number of strings allocated when running callbacks for ActiveRecord instances. I measured that using this script: ``` require 'objspace' require 'active_record' require 'allocation_tracer' ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" ActiveRecord::Base.connection.instance_eval do create_table(:articles) { |t| t.string :name } end class Article < ActiveRecord::Base; end a = Article.create name: "foo" a = Article.find a.id N = 10 result = ObjectSpace::AllocationTracer.trace do N.times { Article.find a.id } end result.sort.each do |k,v| p k => v end puts "total: #{result.values.map(&:first).inject(:+)}" ``` When I run this against master and this branch I get this output: ``` pete@balloon:~/projects/rails/activerecord$ git checkout master M Gemfile Switched to branch 'master' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_before pete@balloon:~/projects/rails/activerecord$ git checkout remove-dynamic-send-on-built-in-callbacks M Gemfile Switched to branch 'remove-dynamic-send-on-built-in-callbacks' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_after pete@balloon:~/projects/rails/activerecord$ diff allocations_before allocations_after 39d38 < {["/home/pete/projects/rails/activesupport/lib/active_support/callbacks.rb", 81]=>[40, 0, 0, 0, 0, 0]} 42c41 < total: 630 --- > total: 590 ``` In addition to this, there are two micro-optimizations present: * Using `block.call if block` vs `yield if block_given?` when the block was being captured already. ``` pete@balloon:~/projects$ cat benchmark_block_call_vs_yield.rb require 'benchmark/ips' def block_capture_with_yield &block yield if block_given? end def block_capture_with_call &block block.call if block end def no_block_capture yield if block_given? end Benchmark.ips do |b| b.report("block_capture_with_yield") { block_capture_with_yield } b.report("block_capture_with_call") { block_capture_with_call } b.report("no_block_capture") { no_block_capture } end pete@balloon:~/projects$ ruby benchmark_block_call_vs_yield.rb Calculating ------------------------------------- block_capture_with_yield 124979 i/100ms block_capture_with_call 138340 i/100ms no_block_capture 136827 i/100ms ------------------------------------------------- block_capture_with_yield 5703108.9 (±2.4%) i/s - 28495212 in 4.999368s block_capture_with_call 6840730.5 (±3.6%) i/s - 34169980 in 5.002649s no_block_capture 5821141.4 (±2.8%) i/s - 29144151 in 5.010580s ``` * Defining and calling methods instead of using send. ``` pete@balloon:~/projects$ cat benchmark_method_call_vs_send.rb require 'benchmark/ips' class Foo def tacos nil end end my_foo = Foo.new Benchmark.ips do |b| b.report('send') { my_foo.send('tacos') } b.report('call') { my_foo.tacos } end pete@balloon:~/projects$ ruby benchmark_method_call_vs_send.rb Calculating ------------------------------------- send 97736 i/100ms call 151142 i/100ms ------------------------------------------------- send 2683730.3 (±2.8%) i/s - 13487568 in 5.029763s call 8005963.9 (±2.7%) i/s - 40052630 in 5.006604s ``` The result of this is making typical ActiveRecord operations slightly faster: https://gist.github.com/phiggins/e46e51dcc7edb45b5f98
2014-09-28 17:42:26 -04:00
module_eval <<-RUBY, __FILE__, __LINE__ + 1
def _run_#{name}_callbacks(&block)
Reduce allocations when running AR callbacks. Inspired by @tenderlove's work in c363fff29f060e6a2effe1e4bb2c4dd4cd805d6e, this reduces the number of strings allocated when running callbacks for ActiveRecord instances. I measured that using this script: ``` require 'objspace' require 'active_record' require 'allocation_tracer' ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" ActiveRecord::Base.connection.instance_eval do create_table(:articles) { |t| t.string :name } end class Article < ActiveRecord::Base; end a = Article.create name: "foo" a = Article.find a.id N = 10 result = ObjectSpace::AllocationTracer.trace do N.times { Article.find a.id } end result.sort.each do |k,v| p k => v end puts "total: #{result.values.map(&:first).inject(:+)}" ``` When I run this against master and this branch I get this output: ``` pete@balloon:~/projects/rails/activerecord$ git checkout master M Gemfile Switched to branch 'master' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_before pete@balloon:~/projects/rails/activerecord$ git checkout remove-dynamic-send-on-built-in-callbacks M Gemfile Switched to branch 'remove-dynamic-send-on-built-in-callbacks' pete@balloon:~/projects/rails/activerecord$ bundle exec ruby benchmark_allocation_with_callback_send.rb > allocations_after pete@balloon:~/projects/rails/activerecord$ diff allocations_before allocations_after 39d38 < {["/home/pete/projects/rails/activesupport/lib/active_support/callbacks.rb", 81]=>[40, 0, 0, 0, 0, 0]} 42c41 < total: 630 --- > total: 590 ``` In addition to this, there are two micro-optimizations present: * Using `block.call if block` vs `yield if block_given?` when the block was being captured already. ``` pete@balloon:~/projects$ cat benchmark_block_call_vs_yield.rb require 'benchmark/ips' def block_capture_with_yield &block yield if block_given? end def block_capture_with_call &block block.call if block end def no_block_capture yield if block_given? end Benchmark.ips do |b| b.report("block_capture_with_yield") { block_capture_with_yield } b.report("block_capture_with_call") { block_capture_with_call } b.report("no_block_capture") { no_block_capture } end pete@balloon:~/projects$ ruby benchmark_block_call_vs_yield.rb Calculating ------------------------------------- block_capture_with_yield 124979 i/100ms block_capture_with_call 138340 i/100ms no_block_capture 136827 i/100ms ------------------------------------------------- block_capture_with_yield 5703108.9 (±2.4%) i/s - 28495212 in 4.999368s block_capture_with_call 6840730.5 (±3.6%) i/s - 34169980 in 5.002649s no_block_capture 5821141.4 (±2.8%) i/s - 29144151 in 5.010580s ``` * Defining and calling methods instead of using send. ``` pete@balloon:~/projects$ cat benchmark_method_call_vs_send.rb require 'benchmark/ips' class Foo def tacos nil end end my_foo = Foo.new Benchmark.ips do |b| b.report('send') { my_foo.send('tacos') } b.report('call') { my_foo.tacos } end pete@balloon:~/projects$ ruby benchmark_method_call_vs_send.rb Calculating ------------------------------------- send 97736 i/100ms call 151142 i/100ms ------------------------------------------------- send 2683730.3 (±2.8%) i/s - 13487568 in 5.029763s call 8005963.9 (±2.7%) i/s - 40052630 in 5.006604s ``` The result of this is making typical ActiveRecord operations slightly faster: https://gist.github.com/phiggins/e46e51dcc7edb45b5f98
2014-09-28 17:42:26 -04:00
_run_callbacks(_#{name}_callbacks, &block)
end
RUBY
end
end
protected
def get_callbacks(name)
send "_#{name}_callbacks"
end
def set_callbacks(name, callbacks)
send "_#{name}_callbacks=", callbacks
end
end
end
end