2019-05-03 06:17:27 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2013-05-07 12:39:01 +08:00
|
|
|
module Trashable
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2020-12-22 07:38:59 +08:00
|
|
|
default_scope { where(deleted_at: nil) }
|
|
|
|
scope :with_deleted, -> { unscope(where: :deleted_at) }
|
2023-02-08 02:28:59 +08:00
|
|
|
scope :only_deleted, -> { with_deleted.where.not(deleted_at: nil) }
|
2013-05-07 12:46:46 +08:00
|
|
|
|
2013-07-10 03:20:18 +08:00
|
|
|
belongs_to :deleted_by, class_name: "User"
|
2013-05-07 12:39:01 +08:00
|
|
|
end
|
|
|
|
|
2013-07-12 04:38:46 +08:00
|
|
|
def trashed?
|
|
|
|
deleted_at.present?
|
|
|
|
end
|
|
|
|
|
2013-07-10 03:20:18 +08:00
|
|
|
def trash!(trashed_by = nil)
|
2013-05-07 12:50:02 +08: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-10 03:20:18 +08:00
|
|
|
trash_update(DateTime.now, trashed_by.try(:id))
|
2013-05-07 12:39:01 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def recover!
|
2013-07-10 03:20:18 +08:00
|
|
|
trash_update(nil, nil)
|
2013-05-07 12:39:01 +08:00
|
|
|
end
|
|
|
|
|
2013-07-10 03:20:18 +08:00
|
|
|
private
|
|
|
|
|
|
|
|
def trash_update(deleted_at, deleted_by_id)
|
2018-06-05 15:29:17 +08:00
|
|
|
self.update_columns(deleted_at: deleted_at, deleted_by_id: deleted_by_id)
|
2013-07-10 03:20:18 +08:00
|
|
|
end
|
2013-05-07 12:39:01 +08:00
|
|
|
end
|