Skip to content

Instantly share code, notes, and snippets.

@rossta
Created October 17, 2011 12:27
Show Gist options
  • Select an option

  • Save rossta/1292502 to your computer and use it in GitHub Desktop.

Select an option

Save rossta/1292502 to your computer and use it in GitHub Desktop.
Enable :background => true option for active record callbacks + "send_later"
ActiveRecord::Base.class_eval do
public :callback
def self.define_background_callback(callback_name)
class_eval <<-RUBY
define_callbacks :background_#{callback_name} # define_callbacks :background_after_create
#
#{callback_name} do |object| # after_create do |object|
object.queue_background_callbacks(:#{callback_name}) # object.queue_background_callbacks(:after_create)
end # end
#
def self.#{callback_name}_with_background(*methods) # def self.after_create_with_background(*methods)
options = methods.extract_options! # options = methods.extract_options!
methods.push(options.except(:background)) # methods.push(options.except(:background))
#
if options[:background] # if options[:background]
background_#{callback_name}(*methods) # background_after_create(*methods)
else # else
#{callback_name}_without_background(*methods) # after_create_without_background(*methods)
end # end
end # end
#
class << self # class << self
alias_method_chain :#{callback_name}, :background # alias_method_chain :after_create, :background
end # end
RUBY
end
BACKGROUND_CALLBACKS = [:after_save, :after_create, :after_update]
BACKGROUND_CALLBACKS.each do |callback_name|
define_background_callback callback_name
end
def queue_background_callbacks(callback_name)
return if self.class.send("background_#{callback_name}_callback_chain").empty?
send_later(:run_background_callbacks, callback_name)
end
def run_background_callbacks(callback_name)
ActiveRecord::Base.transaction do
callback("background_#{callback_name}".to_sym)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment