FIX: Clean up stale `UserExport` records daily.

* Add tests for `UserExport.remove_old_exports`
This commit is contained in:
Guo Xiang Tan 2018-06-05 09:41:40 +08:00
parent dcba320bf6
commit d600e71b3d
3 changed files with 34 additions and 5 deletions

View File

@ -1,9 +1,9 @@
module Jobs
class CleanUpExports < Jobs::Scheduled
every 2.day
every 1.day
def execute(args)
UserExport.remove_old_exports # delete exported CSV files older than 2 days
UserExport.remove_old_exports
end
end
end

View File

@ -1,12 +1,13 @@
class UserExport < ActiveRecord::Base
belongs_to :user
def self.remove_old_exports
UserExport.where('created_at < ?', 2.days.ago).find_each do |expired_export|
file_name = "#{expired_export.file_name}-#{expired_export.id}.csv.gz"
UserExport.where('created_at < ?', 2.days.ago).find_each do |user_export|
file_name = "#{user_export.file_name}-#{user_export.id}.csv.gz"
file_path = "#{UserExport.base_directory}/#{file_name}"
File.delete(file_path) if File.exist?(file_path)
expired_export.destroy
user_export.destroy!
end
end

View File

@ -0,0 +1,28 @@
require 'rails_helper'
RSpec.describe UserExport do
let(:user) { Fabricate(:user) }
describe '.remove_old_exports' do
it 'should remove the right records' do
export = UserExport.create!(
file_name: "test",
user: user,
created_at: 3.days.ago
)
export2 = UserExport.create!(
file_name: "test2",
user: user,
created_at: 1.day.ago
)
expect do
UserExport.remove_old_exports
end.to change { UserExport.count }.by(-1)
expect(UserExport.exists?(id: export.id)).to eq(false)
expect(UserExport.exists?(id: export2.id)).to eq(true)
end
end
end