discourse/lib/trashable.rb

65 lines
1.6 KiB
Ruby
Raw Normal View History

module Trashable
extend ActiveSupport::Concern
included do
default_scope { where(with_deleted_scope_sql) }
2013-05-06 23:46:46 -05:00
# scope unscoped does not work
2013-07-09 14:20:18 -05:00
belongs_to :deleted_by, class_name: 'User'
end
module ClassMethods
def with_deleted
2013-05-06 23:46:46 -05: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
#
scope = rails4? ? self.all.with_default_scope : self.scoped.with_default_scope
scope.where_values.delete(with_deleted_scope_sql)
scope
end
def with_deleted_scope_sql
2013-07-23 13:42:52 -05:00
if rails4?
all.table[:deleted_at].eq(nil).to_sql
else
scoped.table[:deleted_at].eq(nil).to_sql
end
end
end
def trashed?
deleted_at.present?
end
2013-07-09 14:20:18 -05:00
def trash!(trashed_by=nil)
2013-05-06 23:50:02 -05: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 14:20:18 -05:00
trash_update(DateTime.now, trashed_by.try(:id))
end
def recover!
2013-07-09 14:20:18 -05:00
trash_update(nil, nil)
end
2013-07-09 14:20:18 -05:00
private
def trash_update(deleted_at, deleted_by_id)
# see: https://github.com/rails/rails/issues/8436
#
# Fixed in Rails 4
#
self.class.unscoped.where(id: self.id).update_all(deleted_at: deleted_at, deleted_by_id: deleted_by_id)
raw_write_attribute :deleted_at, deleted_at
raw_write_attribute :deleted_by_id, deleted_by_id
end
end