Class: Cron::TrimCollection

Inherits:
Job show all
Defined in:
lib/app/jobs/cron/trim_collection.rb

Overview

Clean up the collection items that have not been updated in 30 days

Instance Attribute Summary

Attributes inherited from ApplicationJob

#payload, #started_at

Instance Method Summary collapse

Methods inherited from Job

cron_tab_entry, #notify_job_failure, #send_support_email

Methods inherited from ApplicationJob

#duration, #parse_payload, #perform, valid_environment?, valid_environments

Methods included from App47Logger

clean_params, #clean_params, delete_parameter_keys, #log_controller_error, log_debug, #log_debug, log_error, #log_error, log_exception, #log_message, log_message, #log_warn, log_warn, mask_parameter_keys, #update_flash_messages

Instance Method Details

#allowed_timeObject

Allowed time the amount of time allowed to exists before deleting



59
60
61
# File 'lib/app/jobs/cron/trim_collection.rb', line 59

def allowed_time
  30.days.ago.utc
end

#allowed_time_for_item(item) ⇒ Object

Try to get a TTL from System configuration, otherwise return the default



50
51
52
53
54
# File 'lib/app/jobs/cron/trim_collection.rb', line 50

def allowed_time_for_item(item)
  SystemConfiguration.send("#{item.class.to_s.underscore}_ttl").days.ago
rescue StandardError
  allowed_time
end

#archive?(item) ⇒ Boolean

Test if this should be archived

Returns:

  • (Boolean)


33
34
35
36
37
38
# File 'lib/app/jobs/cron/trim_collection.rb', line 33

def archive?(item)
  item.send(comparison_field) < allowed_time_for_item(item)
rescue StandardError => error
  App47Logger.log_warn "Unable to archive item #{item.inspect}", error
  false
end

#comparison_fieldObject

Return which field to use for comparison when trimming objects



43
44
45
# File 'lib/app/jobs/cron/trim_collection.rb', line 43

def comparison_field
  :updated_at
end

#executeObject

Fetch each item and delete it if hasn’t been updated in 30 days



12
13
14
15
16
17
18
19
# File 'lib/app/jobs/cron/trim_collection.rb', line 12

def execute
  count = 0
  total = collection.count
  while count <= total
    collection.limit(250).skip(count).each { |item| trim_item(item) if archive?(item) }
    count += 250
  end
end

#trim_item(item) ⇒ Object

Try to safely destroy the item, warn if not successful



24
25
26
27
28
# File 'lib/app/jobs/cron/trim_collection.rb', line 24

def trim_item(item)
  item.destroy
rescue StandardError => error
  App47Logger.log_error "Unable to destroy item #{item.inspect}", error
end