Class: WorkerPlugins::DeleteOldWorkplaces
- Inherits:
-
ApplicationService
- Object
- ServicePattern::Service
- ApplicationService
- WorkerPlugins::DeleteOldWorkplaces
- Defined in:
- app/services/worker_plugins/delete_old_workplaces.rb
Instance Method Summary collapse
-
#perform ⇒ Object
Deletes workplaces that haven’t seen any activity since ‘older_than.ago` — both the workplace record itself is older than the cutoff and none of its links have been created / updated since.
- #stale_workplaces(cutoff) ⇒ Object
Methods inherited from ApplicationService
#db_now_value, #mysql?, #postgres?, #quote, #quote_column, #quote_table, #relation_unscoped?, #sqlite?
Instance Method Details
#perform ⇒ Object
Deletes workplaces that haven’t seen any activity since ‘older_than.ago` —both the workplace record itself is older than the cutoff and none of its links have been created / updated since. Links on deleted workplaces are removed with the parent via `dependent: :destroy`, but this service uses raw `delete_all` in batches to skip per-row callbacks and keep long-running cleanup jobs cheap.
Intended to be scheduled by the consumer application from a Sidekiq worker (or equivalent) — the gem does not register a scheduler of its own.
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'app/services/worker_plugins/delete_old_workplaces.rb', line 15 def perform cutoff = older_than.ago workplaces_deleted = 0 links_deleted = 0 stale_workplaces(cutoff).in_batches(of: batch_size) do |batch| batch_ids = batch.pluck(:id) links_deleted += WorkerPlugins::WorkplaceLink .where(workplace_id: batch_ids) .delete_all workplaces_deleted += WorkerPlugins::Workplace .where(id: batch_ids) .delete_all end succeed!(workplaces_deleted:, links_deleted:) end |
#stale_workplaces(cutoff) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'app/services/worker_plugins/delete_old_workplaces.rb', line 34 def stale_workplaces(cutoff) workplaces_table = quote_table(WorkerPlugins::Workplace.table_name) links_table = quote_table(WorkerPlugins::WorkplaceLink.table_name) WorkerPlugins::Workplace .where("#{workplaces_table}.#{quote_column(:updated_at)} < ?", cutoff) .where(<<~SQL.squish, cutoff) NOT EXISTS ( SELECT 1 FROM #{links_table} WHERE #{links_table}.#{quote_column(:workplace_id)} = #{workplaces_table}.#{quote_column(:id)} AND #{links_table}.#{quote_column(:updated_at)} >= ? ) SQL end |