Last active
December 28, 2015 22:49
-
-
Save mockdeep/7574103 to your computer and use it in GitHub Desktop.
module to make accidentally deleting records really hard
This file contains hidden or 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
module Trashable | |
module ClassMethods | |
def dependent_associations | |
reflect_on_all_associations.select do |association| | |
[:destroy, :delete_all].include?(association.options[:dependent]) | |
end | |
end | |
def trashable_associations | |
dependent_associations.select do |association| | |
association.klass.trashable? | |
end | |
end | |
def deleted | |
unscoped.where(arel_table[:deleted_at].not_eq(nil)) | |
end | |
end | |
def self.included(base) | |
base.class_eval <<-EOS, __FILE__, __LINE__ + 1 | |
alias_method :destroy_for_real, :destroy | |
alias_method :delete_for_real, :delete | |
def destroy | |
run_callbacks(:destroy) do | |
update_column(:deleted_at, Time.zone.now) | |
end | |
end | |
def delete | |
destroy | |
end | |
def restore | |
update_attribute(:deleted_at, nil) | |
restore_associations | |
end | |
def restore_associations | |
self.class.trashable_associations.each do |reflection| | |
reflection_scope(reflection).each(&:restore) | |
end | |
end | |
def reflection_scope(reflection) | |
scope = reflection.klass.deleted | |
scope.merge(association(reflection.name).association_scope) | |
end | |
default_scope { where(deleted_at: nil) } | |
EOS | |
base.send :extend, ClassMethods | |
end | |
end | |
module ActiveRecord | |
class Base | |
def self.trashable? | |
included_modules.include?(Trashable) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment