Skip to content

Instantly share code, notes, and snippets.

@Fivell
Forked from bogdan/callbacks.rb
Created July 26, 2013 08:30
Show Gist options
  • Save Fivell/6087234 to your computer and use it in GitHub Desktop.
Save Fivell/6087234 to your computer and use it in GitHub Desktop.
def set_callback(name, *filter_list, &block)
mapped = nil
__update_callbacks(name, filter_list, block) do |target, chain, type, filters, options|
mapped ||= filters.map do |filter|
Callback.new(chain, filter, type, options.dup, self)
end
filters.each do |filter|
chain.delete_if {|c| c.matches?(type, filter) }
end
options[:prepend] ? chain.unshift(*(mapped.reverse)) : chain.push(*mapped)
target.send("_#{name}_callbacks=", chain)
end
end
def __update_callbacks(name, filters = [], block = nil) #:nodoc:
type = filters.first.in?([:before, :after, :around]) ? filters.shift : :before
options = filters.last.is_a?(Hash) ? filters.pop : {}
filters.unshift(block) if block
([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target|
chain = target.send("_#{name}_callbacks")
yield target, chain.dup, type, filters, options
target.__reset_runner(name)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment