From c323af398947d3a61b5b5ac61c6a7b9645392692 Mon Sep 17 00:00:00 2001 From: hughkelsey Date: Sun, 3 Mar 2024 22:10:53 -0800 Subject: [PATCH] Use the writing role for increment_usage_count (#170) * use the writing role for increment_usage_count * Make this backwards compatible with Rails < 6 * Broadcast when Shortener::ShortenedUrl is loaded * Documented 'Configuring Reader and Writer Multi-DB Roles' --- README.rdoc | 24 +++++++++++++++++++----- app/models/shortener/shortened_url.rb | 2 ++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/README.rdoc b/README.rdoc index b28140f..be2a838 100644 --- a/README.rdoc +++ b/README.rdoc @@ -260,14 +260,28 @@ If you want more things to happen when a user accesses one of your short urls, y You can store a `shortened_urls` table in another database and connecting to it by creating a initializer with the following: -```ruby -ActiveSupport.on_load(:shortener_record) do - connects_to(database: { writing: :dbname, reading: :dbname_replica }) -end -``` + ActiveSupport.on_load(:shortener_record) do + connects_to(database: { writing: :dbname, reading: :dbname_replica }) + end **Note:** Please, replace `dbname` and `dbname_replica` to match your database configuration. +=== Configuring Reader and Writer Multi-DB Roles + +Shortener has one write operation that happens on a GET request. To allow this you can override this method in an initializer. + + module ShortenerWriterMonkeyPatch + def increment_usage_count + ActiveRecord::Base.connected_to(role: :writing) do + self.class.increment_counter(:use_count, id) + end + end + end + + ActiveSupport.on_load(:shortener_shortened_url) do + Shortener::ShortenedUrl.prepend(ShortenerWriterMonkeyPatch) + end + == Contributing We welcome new contributors. Because we're all busy people, and because Shortener diff --git a/app/models/shortener/shortened_url.rb b/app/models/shortener/shortened_url.rb index 02aae10..b557ec8 100644 --- a/app/models/shortener/shortened_url.rb +++ b/app/models/shortener/shortened_url.rb @@ -147,3 +147,5 @@ def generate_unique_key(retries = Shortener.persist_retries) end end end + +ActiveSupport.run_load_hooks :shortener_shortened_url, Shortener::ShortenedUrl \ No newline at end of file