From dc05d7ece4e5c485eeb7c423e1cf69d1d2596312 Mon Sep 17 00:00:00 2001 From: Andrew Brown Date: Wed, 30 Jun 2021 17:31:26 -0700 Subject: [PATCH] cache doc word counts --- app/jobs/save_document_revision_job.rb | 3 +++ app/models/documents/document.rb | 5 ++++- .../20210701002938_add_cached_word_count_to_documents.rb | 5 +++++ db/schema.rb | 3 ++- 4 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 db/migrate/20210701002938_add_cached_word_count_to_documents.rb diff --git a/app/jobs/save_document_revision_job.rb b/app/jobs/save_document_revision_job.rb index b682109b..3fb83f7f 100644 --- a/app/jobs/save_document_revision_job.rb +++ b/app/jobs/save_document_revision_job.rb @@ -7,6 +7,9 @@ class SaveDocumentRevisionJob < ApplicationJob document = Document.find(document_id) return unless document.present? + # Update cached word count for the document regardless of how often this is called + document.update(cached_word_count: document.computed_word_count) + # Make sure we're only storing revisions at least every 5 min latest_revision = document.document_revisions.order('created_at DESC').limit(1).first if latest_revision.present? && latest_revision.created_at > 5.minutes.ago diff --git a/app/models/documents/document.rb b/app/models/documents/document.rb index 060e3197..c4e9d31c 100644 --- a/app/models/documents/document.rb +++ b/app/models/documents/document.rb @@ -77,7 +77,10 @@ class Document < ApplicationRecord end def word_count - # TODO this should probably be cached !! + self.cached_word_count || self.computed_word_count + end + + def computed_word_count (self.body || "").split(/\s+/).count end diff --git a/db/migrate/20210701002938_add_cached_word_count_to_documents.rb b/db/migrate/20210701002938_add_cached_word_count_to_documents.rb new file mode 100644 index 00000000..4fa0d0c2 --- /dev/null +++ b/db/migrate/20210701002938_add_cached_word_count_to_documents.rb @@ -0,0 +1,5 @@ +class AddCachedWordCountToDocuments < ActiveRecord::Migration[6.0] + def change + add_column :documents, :cached_word_count, :integer + end +end diff --git a/db/schema.rb b/db/schema.rb index 44d95a06..08c9a272 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema.define(version: 2021_06_27_023405) do +ActiveRecord::Schema.define(version: 2021_07_01_002938) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false @@ -1190,6 +1190,7 @@ ActiveRecord::Schema.define(version: 2021_06_27_023405) do t.boolean "favorite" t.text "notes_text" t.integer "folder_id" + t.integer "cached_word_count" t.index ["folder_id"], name: "index_documents_on_folder_id" t.index ["universe_id", "deleted_at"], name: "index_documents_on_universe_id_and_deleted_at" t.index ["universe_id"], name: "index_documents_on_universe_id"