diff --git a/app/models/publish_intent.rb b/app/models/publish_intent.rb index b2b1085d..b59bcad9 100644 --- a/app/models/publish_intent.rb +++ b/app/models/publish_intent.rb @@ -47,6 +47,11 @@ def content_item ContentItem.where(base_path:).first end + # Called nightly from a cron job + def self.cleanup_expired + where("publish_time < ?", PUBLISH_TIME_LEEWAY.ago).delete_all + end + def base_path_without_root base_path&.sub(%r{^/}, "") end diff --git a/lib/tasks/housekeeping.rake b/lib/tasks/housekeeping.rake new file mode 100644 index 00000000..b274c08b --- /dev/null +++ b/lib/tasks/housekeeping.rake @@ -0,0 +1,6 @@ +namespace :housekeeping do + desc "Delete any publish intents in the past" + task cleanup_publish_intents: :environment do + PublishIntent.cleanup_expired + end +end diff --git a/spec/models/publish_intent_spec.rb b/spec/models/publish_intent_spec.rb index 1e60ab78..150c6aac 100644 --- a/spec/models/publish_intent_spec.rb +++ b/spec/models/publish_intent_spec.rb @@ -155,4 +155,31 @@ ) end end + + describe ".cleanup_expired" do + before :each do + create(:publish_intent, publish_time: 3.days.ago) + create(:publish_intent, publish_time: 2.days.ago) + create(:publish_intent, publish_time: 1.hour.ago) + create(:publish_intent, publish_time: 10.minutes.from_now) + create(:publish_intent, publish_time: 10.days.from_now) + create(:publish_intent, publish_time: 1.year.from_now) + end + + it "deletes all publish_intents with publish_at in the past" do + PublishIntent.cleanup_expired + + expect(PublishIntent.count).to eq(3) + expect(PublishIntent.where(:publish_time.gte => Time.zone.now).count).to eq(3) + end + + it "does not delete very recently passed intents" do + recent = create(:publish_intent, publish_time: 30.seconds.ago) + + PublishIntent.cleanup_expired + + expect(PublishIntent.where(base_path: recent.base_path).first).to be + expect(PublishIntent.count).to eq(4) + end + end end