Skip to content

Instantly share code, notes, and snippets.

@rafaelcgo
Last active December 26, 2022 20:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelcgo/f2e95f02a1e29d36429b to your computer and use it in GitHub Desktop.
Save rafaelcgo/f2e95f02a1e29d36429b to your computer and use it in GitHub Desktop.
Adding Callbacks to a Rails Concern (BackgroundDestroyable)
# BackgroundDestroyable classes MUST have deleted_at:datetime column
# BackgroundDestroyable enable :background_destroy and :background_restore callbacks
module BackgroundDestroyable
extend ActiveSupport::Concern
include ActiveModel::Callbacks
included do
define_model_callbacks :background_destroy, :background_restore
default_scope { where(deleted_at: nil) }
scope :deleted, -> { unscoped.where.not(deleted_at: nil) }
end
def destroy(mode = :background)
if mode == :background
unless self.deleted_at.present?
run_callbacks :background_destroy do
update_attribute :deleted_at, Time.now
Resque.enqueue(BackgroundDestroyer, self.id, self.class.to_s)
end
end
elsif mode == :now
self.class.uploaders.each do |uploader, uploader_class|
self.send("remove_#{uploader}!")
end
super()
end
end
def destroy_now!
self.destroy(:now) if self.deleted_at
end
def restore
run_callbacks :background_restore do
update_attribute :deleted_at, nil
end
end
end
class Pose < ActiveRecord::Base
include BackgroundDestroyable
belongs_to :photo
validates_presence_of :photo, :pose
before_background_destroy :decrement_multilevel_counter
before_background_restore :increment_multilevel_counter
private
def increment_multilevel_counter
photo.parent.class.increment_counter(:poses_count, photo.parent.id)
end
def decrement_multilevel_counter
photo.parent.class.decrement_counter(:poses_count, photo.parent.id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment