Skip to content
This repository has been archived by the owner on May 7, 2020. It is now read-only.

Clear Old Conversations in ActiveRecord with Clockwork and ActiveJob

Ben edited this page Apr 4, 2016 · 6 revisions

We'll want to make sure that old conversations are removed from the database to conserve space. By that point, the user probably won't expect context to be saved.

I use squeel for SQL queries - but it's not required. My example won't work without it, but it's somewhat simple to replace it with a normal query.

Read clockwork's guide, and make sure you have a solution for running it in production (it doesn't run alongside your app, but instead in it's own process).

You should make sure that you have a good solution for running jobs in the background. I recommend GitHub's resque.

Generator

$ rails generate wit_bot:clear_conversations_job

Guide

First, let's create the job. It doesn't need a high priority in resque, so queue_as should be :low. All that the job needs to do is find all conversations not updated since last 4 hours ago, and destroy them all.

class ClearConversationsJob < ActiveJob::Base
  queue_as :low

  def perform
    # Find all conversations not updated in the last 4 hours, and destroy them.
    Conversation.where{ updated_at <= 4.hours.ago }.destroy_all
  end
end

Now, you'll want to install the clockwork gem (unless you already have job scheduler, in which case, by all means, use that one). Add this to your Gemfile, and bundle.

# For scheduled jobs
gem 'clockwork', '~> 1.2.0'

In the root of your project, create a clock.rb file, and set it to run the ClearConversationsJob every hour:

require 'clockwork'

require_relative 'config/boot'
require_relative 'config/environment'

module Clockwork
  every(1.hour, 'Clear Old Conversations') { ClearConversationsJob.perform_later }
end

And run it:

$ clockwork clock.rb

Yay! Old conversations will be cleared every hour!

Getting Started

Here's how to get started with wit_bot in 3 steps:

  1. Learn how to use wit.ai
  2. Learn how to setup the gem
  3. Learn how to send a message

Dive Deeper

Create Bots

Integrate it

Clone this wiki locally