-
-
Save rafaelcgo/f2e95f02a1e29d36429b to your computer and use it in GitHub Desktop.
Adding Callbacks to a Rails Concern (BackgroundDestroyable)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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