2019-05-02 18:17:27 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-05-07 00:39:01 -04:00
|
|
|
module Trashable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2013-08-15 11:52:18 -04:00
|
|
|
default_scope { where(with_deleted_scope_sql) }
|
2013-05-07 00:46:46 -04:00
|
|
|
|
|
|
|
# scope unscoped does not work
|
2013-07-09 15:20:18 -04:00
|
|
|
belongs_to :deleted_by, class_name: 'User'
|
2013-05-07 00:39:01 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
module ClassMethods
|
|
|
|
def with_deleted
|
2013-05-07 00:46:46 -04:00
|
|
|
# lifted from acts_as_paranoid, works around https://github.com/rails/rails/issues/4306
|
|
|
|
#
|
|
|
|
# with this in place Post.limit(10).with_deleted, will work as expected
|
|
|
|
#
|
2014-05-08 00:14:24 -04:00
|
|
|
scope = self.all
|
2013-08-16 08:53:40 -04:00
|
|
|
|
2019-05-06 21:57:55 -04:00
|
|
|
# must use :send here cause predicates is protected
|
|
|
|
# careful with updates of this API
|
2017-08-31 00:06:56 -04:00
|
|
|
scope.where_clause.send(:predicates).delete(with_deleted_scope_sql)
|
2013-05-07 00:39:01 -04:00
|
|
|
scope
|
|
|
|
end
|
|
|
|
|
|
|
|
def with_deleted_scope_sql
|
2014-02-17 11:44:28 -05:00
|
|
|
all.table[:deleted_at].eq(nil).to_sql
|
2013-05-07 00:39:01 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2013-07-11 16:38:46 -04:00
|
|
|
def trashed?
|
|
|
|
deleted_at.present?
|
|
|
|
end
|
|
|
|
|
2013-07-09 15:20:18 -04:00
|
|
|
def trash!(trashed_by = nil)
|
2013-05-07 00:50:02 -04:00
|
|
|
# note, an argument could be made that the column should probably called trashed_at
|
|
|
|
# however, deleted_at is the terminology used in the UI
|
|
|
|
#
|
|
|
|
# we could hijack use a delete! and delete - redirecting the originals elsewhere, but that is
|
|
|
|
# confusing as well. So for now, we go with trash!
|
|
|
|
#
|
2013-07-09 15:20:18 -04:00
|
|
|
trash_update(DateTime.now, trashed_by.try(:id))
|
2013-05-07 00:39:01 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def recover!
|
2013-07-09 15:20:18 -04:00
|
|
|
trash_update(nil, nil)
|
2013-05-07 00:39:01 -04:00
|
|
|
end
|
|
|
|
|
2013-07-09 15:20:18 -04:00
|
|
|
private
|
|
|
|
|
|
|
|
def trash_update(deleted_at, deleted_by_id)
|
2018-06-05 03:29:17 -04:00
|
|
|
self.update_columns(deleted_at: deleted_at, deleted_by_id: deleted_by_id)
|
2013-07-09 15:20:18 -04:00
|
|
|
end
|
|
|
|
|
2013-05-07 00:39:01 -04:00
|
|
|
end
|