media_attachments_vacuum.rb 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # frozen_string_literal: true
  2. class Vacuum::MediaAttachmentsVacuum
  3. TTL = 1.day.freeze
  4. def initialize(retention_period)
  5. @retention_period = retention_period
  6. end
  7. def perform
  8. vacuum_orphaned_records!
  9. vacuum_cached_files! if retention_period?
  10. end
  11. private
  12. def vacuum_cached_files!
  13. media_attachments_past_retention_period.find_in_batches do |media_attachments|
  14. AttachmentBatch.new(MediaAttachment, media_attachments).clear
  15. end
  16. end
  17. def vacuum_orphaned_records!
  18. orphaned_media_attachments.find_in_batches do |media_attachments|
  19. AttachmentBatch.new(MediaAttachment, media_attachments).delete
  20. end
  21. end
  22. def media_attachments_past_retention_period
  23. MediaAttachment.remote.cached.where(MediaAttachment.arel_table[:created_at].lt(@retention_period.ago)).where(MediaAttachment.arel_table[:updated_at].lt(@retention_period.ago))
  24. end
  25. def orphaned_media_attachments
  26. MediaAttachment.unattached.where(MediaAttachment.arel_table[:created_at].lt(TTL.ago))
  27. end
  28. def retention_period?
  29. @retention_period.present?
  30. end
  31. end