media_attachments_vacuum.rb 1.0 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_each do |media_attachment|
  14. media_attachment.file.destroy
  15. media_attachment.thumbnail.destroy
  16. media_attachment.save
  17. end
  18. end
  19. def vacuum_orphaned_records!
  20. orphaned_media_attachments.in_batches.destroy_all
  21. end
  22. def media_attachments_past_retention_period
  23. MediaAttachment.unscoped.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.unscoped.unattached.where(MediaAttachment.arel_table[:created_at].lt(TTL.ago))
  27. end
  28. def retention_period?
  29. @retention_period.present?
  30. end
  31. end