https://github.com/huacnlee/sidekiq-activerecord-shard
Sidekiq middleware to supports ActiveRecord 7 shard
https://github.com/huacnlee/sidekiq-activerecord-shard
activerecord shard sidekiq
Last synced: 4 months ago
JSON representation
Sidekiq middleware to supports ActiveRecord 7 shard
- Host: GitHub
- URL: https://github.com/huacnlee/sidekiq-activerecord-shard
- Owner: huacnlee
- License: mit
- Created: 2022-06-15T10:16:47.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2022-06-16T02:47:29.000Z (over 3 years ago)
- Last Synced: 2025-06-28T11:05:22.523Z (4 months ago)
- Topics: activerecord, shard, sidekiq
- Language: Ruby
- Homepage:
- Size: 48.8 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Sidekiq Activerecord::Shard Middleware
A Sidekiq middleware for supports ActiveRecord Shard with [ActiveSupport:CurrentAttribute](https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html).
> **Warning**
> This gem can work with [sidekiq-cron](https://github.com/ondrejbartas/sidekiq-cron) or other schedulers, because when Schedule perform a job, they can't know the which shard to use.## Installation
Add this line to your application's Gemfile:
```ruby
gem "sidekiq-activerecord-shard"
```And then execute:
```bash
$ bundle
```## Usage
Create `app/models/current.rb`:
```rb
class Current < ActiveSupport::CurrentAttributes
attribute :tenant_id
end
```Set `Current.tenant_id` on ApplicationController:
```rb
class ApplicationController < ActionController::Base
before_action :set_current_tenant_iddef set_current_tenant_id
Current.tenant_id = request.headers["x-tenant-id"]
end
end
```Add sidekiq config `config/initializers/sidekiq-activerecord-shard.rb`:
```rb
# Enable Sidekiq CurrentAttributes middleware for store Current
require "sidekiq/middleware/current_attributes"
Sidekiq::CurrentAttributes.persist(Current)SidekiqActiveRecordShard.configure do
self.selected_shard = -> do
case Current.tenant_id
when "other"
:other
else
:primary
end
end
end
```### Perform Job by set shared
Some times, you want to perform a job without Request context, or start Job in schedulers.
Now use can use `set(shard: "shard_name")` to set shared in directly.
```rb
# Call job with "other" shard db
MyJob.set(shard: "other").perform_later# Call job with "primary" shard db
MyJob.set(shard: "primary").perform_later
```## Contributing
Contribution directions go here.
## License
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).