2016-02-12 23:52:43 +08:00
|
|
|
module ArchivableModel
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
|
|
|
validates :archived, inclusion: { in: [true, false] }
|
|
|
|
before_save :set_archive_timestamp
|
|
|
|
before_save :set_restore_timestamp
|
2020-12-13 05:46:30 +08:00
|
|
|
|
|
|
|
scope :active, -> { where(archived: false) }
|
|
|
|
scope :archived, -> { where(archived: true) }
|
2016-02-12 23:52:43 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
# Not archived
|
|
|
|
def active?
|
2020-12-13 05:46:30 +08:00
|
|
|
!archived?
|
2016-02-12 23:52:43 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
# Helper for archiving project. Timestamp of archiving is handler by
|
|
|
|
# before_save callback.
|
|
|
|
# Sets the archived_by value to the current user.
|
2020-09-17 23:15:41 +08:00
|
|
|
def archive(current_user)
|
2016-02-12 23:52:43 +08:00
|
|
|
self.archived = true
|
|
|
|
self.archived_by = current_user
|
|
|
|
save
|
|
|
|
end
|
|
|
|
|
|
|
|
# Same as archive but raises exception if archive fails.
|
|
|
|
# Sets the archived_by value to the current user.
|
|
|
|
def archive!(current_user)
|
2021-01-04 22:11:24 +08:00
|
|
|
self.archived = true
|
|
|
|
self.archived_by = current_user
|
|
|
|
save!
|
2016-02-12 23:52:43 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
# Helper for restoring project from archive.
|
|
|
|
# Sets the restored_by value to the current user.
|
2020-09-17 23:15:41 +08:00
|
|
|
def restore(current_user)
|
2016-02-12 23:52:43 +08:00
|
|
|
self.archived = false
|
|
|
|
self.restored_by = current_user
|
|
|
|
save
|
|
|
|
end
|
|
|
|
|
|
|
|
# Same as restore but raises exception if restore fails.
|
|
|
|
# Sets the restored_by value to the current user.
|
|
|
|
def restore!(current_user)
|
2021-01-04 22:11:24 +08:00
|
|
|
self.archived = false
|
|
|
|
self.restored_by = current_user
|
|
|
|
save!
|
2016-02-12 23:52:43 +08:00
|
|
|
end
|
|
|
|
|
2023-06-08 15:54:59 +08:00
|
|
|
def name_with_label
|
|
|
|
raise NotImplementedError, "Archivable model must implement the '.archived_branch?' method!" unless respond_to?(:archived_branch?)
|
2023-06-16 17:32:39 +08:00
|
|
|
return "#{I18n.t('labels.archived')} #{parent&.name || name}" if archived_branch?
|
2023-06-08 16:54:01 +08:00
|
|
|
|
|
|
|
parent&.name || name
|
2023-06-08 15:54:59 +08:00
|
|
|
end
|
|
|
|
|
2016-02-12 23:52:43 +08:00
|
|
|
protected
|
|
|
|
|
|
|
|
def set_archive_timestamp
|
|
|
|
if self.archived_changed?(from: false, to: true)
|
|
|
|
self.archived_on = Time.current.to_formatted_s
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def set_restore_timestamp
|
|
|
|
if self.archived_changed?(from: true, to: false)
|
|
|
|
self.restored_on = Time.current.to_formatted_s
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|