preview_cards_vacuum.rb 969 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. # frozen_string_literal: true
  2. class Vacuum::PreviewCardsVacuum
  3. TTL = 1.day.freeze
  4. def initialize(retention_period)
  5. @retention_period = retention_period
  6. end
  7. def perform
  8. vacuum_cached_images! if retention_period?
  9. vacuum_orphaned_records!
  10. end
  11. private
  12. def vacuum_cached_images!
  13. preview_cards_past_retention_period.find_each do |preview_card|
  14. preview_card.image.destroy
  15. preview_card.save
  16. end
  17. end
  18. def vacuum_orphaned_records!
  19. orphaned_preview_cards.in_batches.destroy_all
  20. end
  21. def preview_cards_past_retention_period
  22. PreviewCard.cached.where(PreviewCard.arel_table[:updated_at].lt(@retention_period.ago))
  23. end
  24. def orphaned_preview_cards
  25. PreviewCard.where('NOT EXISTS (SELECT 1 FROM preview_cards_statuses WHERE preview_cards_statuses.preview_card_id = preview_cards.id)').where(PreviewCard.arel_table[:created_at].lt(TTL.ago))
  26. end
  27. def retention_period?
  28. @retention_period.present?
  29. end
  30. end