Skip to content

Commit

Permalink
Use the writing role for increment_usage_count (#170)
Browse files Browse the repository at this point in the history
* 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'
  • Loading branch information
hughkelsey authored Mar 4, 2024
1 parent c974af5 commit c323af3
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 5 deletions.
24 changes: 19 additions & 5 deletions README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions app/models/shortener/shortened_url.rb
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,5 @@ def generate_unique_key(retries = Shortener.persist_retries)
end
end
end

ActiveSupport.run_load_hooks :shortener_shortened_url, Shortener::ShortenedUrl

0 comments on commit c323af3

Please sign in to comment.