sublet 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +7 -0
- data/.rspec +3 -0
- data/.rubocop.yml +35 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +132 -0
- data/LICENSE.txt +21 -0
- data/README.md +175 -0
- data/Rakefile +12 -0
- data/lib/sublet/controller_helpers.rb +15 -0
- data/lib/sublet/core.rb +121 -0
- data/lib/sublet/current.rb +7 -0
- data/lib/sublet/model.rb +54 -0
- data/lib/sublet/path_resolver.rb +37 -0
- data/lib/sublet/version.rb +5 -0
- data/lib/sublet.rb +48 -0
- data/sig/sublet.rbs +4 -0
- metadata +91 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: bc7c861f1489428e02c4e6473c96a98f37d03203b4771e140bb9da10948862ce
|
4
|
+
data.tar.gz: 4e1f04e4268d6ec183f7fe78d68c4f906176c5378742f70e9175fbdf20291554
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 8105b8d9825d970d632f13173401c24fd750d52fe9e09bc5bceedd264da3faac7660c6673e289703d932bd71ea53f49c28ea85136921dddf03c529334493e726
|
7
|
+
data.tar.gz: ce1e6e3281a28d442e60c3e16f885378dc09a748f01614c18cc619edb825dbda304a0de4ba24c7024c6412a0f023eefa3d409d1b8a6f8b5a57cf92f6a4b58e03
|
data/.rspec
ADDED
data/.rubocop.yml
ADDED
@@ -0,0 +1,35 @@
|
|
1
|
+
AllCops:
|
2
|
+
NewCops: enable
|
3
|
+
SuggestExtensions: false
|
4
|
+
|
5
|
+
Style/Documentation:
|
6
|
+
Enabled: false
|
7
|
+
|
8
|
+
Layout/LineLength:
|
9
|
+
Max: 120
|
10
|
+
Exclude:
|
11
|
+
- 'sublet.gemspec'
|
12
|
+
|
13
|
+
Metrics/AbcSize:
|
14
|
+
Max: 30
|
15
|
+
Exclude:
|
16
|
+
- 'lib/sublet/core.rb'
|
17
|
+
|
18
|
+
Metrics/CyclomaticComplexity:
|
19
|
+
Max: 8
|
20
|
+
Exclude:
|
21
|
+
- 'lib/sublet/core.rb'
|
22
|
+
- 'lib/sublet/path_resolver.rb'
|
23
|
+
|
24
|
+
Metrics/MethodLength:
|
25
|
+
Max: 25
|
26
|
+
Exclude:
|
27
|
+
- 'lib/sublet/core.rb'
|
28
|
+
|
29
|
+
Metrics/PerceivedComplexity:
|
30
|
+
Max: 9
|
31
|
+
Exclude:
|
32
|
+
- 'lib/sublet/core.rb'
|
33
|
+
|
34
|
+
Metrics/ModuleLength:
|
35
|
+
Max: 120
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,132 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our
|
6
|
+
community a harassment-free experience for everyone, regardless of age, body
|
7
|
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8
|
+
identity and expression, level of experience, education, socio-economic status,
|
9
|
+
nationality, personal appearance, race, caste, color, religion, or sexual
|
10
|
+
identity and orientation.
|
11
|
+
|
12
|
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
13
|
+
diverse, inclusive, and healthy community.
|
14
|
+
|
15
|
+
## Our Standards
|
16
|
+
|
17
|
+
Examples of behavior that contributes to a positive environment for our
|
18
|
+
community include:
|
19
|
+
|
20
|
+
* Demonstrating empathy and kindness toward other people
|
21
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
22
|
+
* Giving and gracefully accepting constructive feedback
|
23
|
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
24
|
+
and learning from the experience
|
25
|
+
* Focusing on what is best not just for us as individuals, but for the overall
|
26
|
+
community
|
27
|
+
|
28
|
+
Examples of unacceptable behavior include:
|
29
|
+
|
30
|
+
* The use of sexualized language or imagery, and sexual attention or advances of
|
31
|
+
any kind
|
32
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
33
|
+
* Public or private harassment
|
34
|
+
* Publishing others' private information, such as a physical or email address,
|
35
|
+
without their explicit permission
|
36
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
37
|
+
professional setting
|
38
|
+
|
39
|
+
## Enforcement Responsibilities
|
40
|
+
|
41
|
+
Community leaders are responsible for clarifying and enforcing our standards of
|
42
|
+
acceptable behavior and will take appropriate and fair corrective action in
|
43
|
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
44
|
+
or harmful.
|
45
|
+
|
46
|
+
Community leaders have the right and responsibility to remove, edit, or reject
|
47
|
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
48
|
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
49
|
+
decisions when appropriate.
|
50
|
+
|
51
|
+
## Scope
|
52
|
+
|
53
|
+
This Code of Conduct applies within all community spaces, and also applies when
|
54
|
+
an individual is officially representing the community in public spaces.
|
55
|
+
Examples of representing our community include using an official email address,
|
56
|
+
posting via an official social media account, or acting as an appointed
|
57
|
+
representative at an online or offline event.
|
58
|
+
|
59
|
+
## Enforcement
|
60
|
+
|
61
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
62
|
+
reported to the community leaders responsible for enforcement at
|
63
|
+
[INSERT CONTACT METHOD].
|
64
|
+
All complaints will be reviewed and investigated promptly and fairly.
|
65
|
+
|
66
|
+
All community leaders are obligated to respect the privacy and security of the
|
67
|
+
reporter of any incident.
|
68
|
+
|
69
|
+
## Enforcement Guidelines
|
70
|
+
|
71
|
+
Community leaders will follow these Community Impact Guidelines in determining
|
72
|
+
the consequences for any action they deem in violation of this Code of Conduct:
|
73
|
+
|
74
|
+
### 1. Correction
|
75
|
+
|
76
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
77
|
+
unprofessional or unwelcome in the community.
|
78
|
+
|
79
|
+
**Consequence**: A private, written warning from community leaders, providing
|
80
|
+
clarity around the nature of the violation and an explanation of why the
|
81
|
+
behavior was inappropriate. A public apology may be requested.
|
82
|
+
|
83
|
+
### 2. Warning
|
84
|
+
|
85
|
+
**Community Impact**: A violation through a single incident or series of
|
86
|
+
actions.
|
87
|
+
|
88
|
+
**Consequence**: A warning with consequences for continued behavior. No
|
89
|
+
interaction with the people involved, including unsolicited interaction with
|
90
|
+
those enforcing the Code of Conduct, for a specified period of time. This
|
91
|
+
includes avoiding interactions in community spaces as well as external channels
|
92
|
+
like social media. Violating these terms may lead to a temporary or permanent
|
93
|
+
ban.
|
94
|
+
|
95
|
+
### 3. Temporary Ban
|
96
|
+
|
97
|
+
**Community Impact**: A serious violation of community standards, including
|
98
|
+
sustained inappropriate behavior.
|
99
|
+
|
100
|
+
**Consequence**: A temporary ban from any sort of interaction or public
|
101
|
+
communication with the community for a specified period of time. No public or
|
102
|
+
private interaction with the people involved, including unsolicited interaction
|
103
|
+
with those enforcing the Code of Conduct, is allowed during this period.
|
104
|
+
Violating these terms may lead to a permanent ban.
|
105
|
+
|
106
|
+
### 4. Permanent Ban
|
107
|
+
|
108
|
+
**Community Impact**: Demonstrating a pattern of violation of community
|
109
|
+
standards, including sustained inappropriate behavior, harassment of an
|
110
|
+
individual, or aggression toward or disparagement of classes of individuals.
|
111
|
+
|
112
|
+
**Consequence**: A permanent ban from any sort of public interaction within the
|
113
|
+
community.
|
114
|
+
|
115
|
+
## Attribution
|
116
|
+
|
117
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
118
|
+
version 2.1, available at
|
119
|
+
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
|
120
|
+
|
121
|
+
Community Impact Guidelines were inspired by
|
122
|
+
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
|
123
|
+
|
124
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
125
|
+
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
|
126
|
+
[https://www.contributor-covenant.org/translations][translations].
|
127
|
+
|
128
|
+
[homepage]: https://www.contributor-covenant.org
|
129
|
+
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
|
130
|
+
[Mozilla CoC]: https://github.com/mozilla/diversity
|
131
|
+
[FAQ]: https://www.contributor-covenant.org/faq
|
132
|
+
[translations]: https://www.contributor-covenant.org/translations
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2025 GoGrow, Inc
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,175 @@
|
|
1
|
+
# Sublet
|
2
|
+
|
3
|
+
Hierarchy-aware, **opt-in multi-tenancy** for ActiveRecord.
|
4
|
+
|
5
|
+
- Declare a **tenant root** with `sublet`.
|
6
|
+
- Declare **subletters** with `subletter(:parent_assoc)` — the parent can be the tenant or another subletter.
|
7
|
+
- You set `Sublet.current_tenant` yourself (only in the controllers you want).
|
8
|
+
- Sublet auto-scopes queries via `default_scope` so admin filters, counts, etc. follow the tenant.
|
9
|
+
- **Fails open** when tenant chains can't be resolved (no scoping applied).
|
10
|
+
- Includes **automatic validation** to prevent tenant mismatches.
|
11
|
+
|
12
|
+
## Install
|
13
|
+
|
14
|
+
Add this line to your application's Gemfile:
|
15
|
+
|
16
|
+
```ruby
|
17
|
+
gem "sublet", "~> 0.1.0"
|
18
|
+
```
|
19
|
+
|
20
|
+
And then execute:
|
21
|
+
|
22
|
+
```bash
|
23
|
+
bundle install
|
24
|
+
```
|
25
|
+
|
26
|
+
Or install it yourself as:
|
27
|
+
|
28
|
+
```bash
|
29
|
+
gem install sublet
|
30
|
+
```
|
31
|
+
|
32
|
+
### Requirements
|
33
|
+
|
34
|
+
- Ruby >= 3.1.0
|
35
|
+
- ActiveRecord >= 6.1
|
36
|
+
- ActiveSupport >= 6.1
|
37
|
+
|
38
|
+
## Usage
|
39
|
+
|
40
|
+
### Basic Setup
|
41
|
+
|
42
|
+
```ruby
|
43
|
+
class Company < ApplicationRecord
|
44
|
+
include Sublet::Model
|
45
|
+
sublet
|
46
|
+
end
|
47
|
+
|
48
|
+
class Department < ApplicationRecord
|
49
|
+
include Sublet::Model
|
50
|
+
subletter(:company)
|
51
|
+
belongs_to :company
|
52
|
+
end
|
53
|
+
|
54
|
+
class Employee < ApplicationRecord
|
55
|
+
include Sublet::Model
|
56
|
+
subletter(:department)
|
57
|
+
belongs_to :department
|
58
|
+
has_one :company, through: :department
|
59
|
+
end
|
60
|
+
```
|
61
|
+
|
62
|
+
### Controller Integration
|
63
|
+
|
64
|
+
In a controller where you want tenant scoping:
|
65
|
+
|
66
|
+
```ruby
|
67
|
+
class Admin::BaseController < ApplicationController
|
68
|
+
before_action do
|
69
|
+
Sublet.current_tenant = current_user.company
|
70
|
+
end
|
71
|
+
end
|
72
|
+
```
|
73
|
+
|
74
|
+
Or use the included controller helper:
|
75
|
+
|
76
|
+
```ruby
|
77
|
+
class Admin::BaseController < ApplicationController
|
78
|
+
before_action do
|
79
|
+
set_current_sublet(current_user.company)
|
80
|
+
end
|
81
|
+
end
|
82
|
+
```
|
83
|
+
|
84
|
+
### Temporary Tenant Switching
|
85
|
+
|
86
|
+
```ruby
|
87
|
+
# Temporarily switch to a different tenant
|
88
|
+
Sublet.with_tenant(Company.find(1)) do
|
89
|
+
Employee.count # Scoped to Company 1
|
90
|
+
end
|
91
|
+
|
92
|
+
# Temporarily bypass tenant scoping
|
93
|
+
Sublet.without_tenant do
|
94
|
+
Employee.unscoped.count # All employees across all tenants
|
95
|
+
end
|
96
|
+
```
|
97
|
+
|
98
|
+
### Advanced Examples
|
99
|
+
|
100
|
+
#### Multi-level Hierarchy
|
101
|
+
|
102
|
+
```ruby
|
103
|
+
class Account < ApplicationRecord
|
104
|
+
include Sublet::Model
|
105
|
+
sublet
|
106
|
+
end
|
107
|
+
|
108
|
+
class Company < ApplicationRecord
|
109
|
+
include Sublet::Model
|
110
|
+
subletter(:account)
|
111
|
+
belongs_to :account
|
112
|
+
end
|
113
|
+
|
114
|
+
class Department < ApplicationRecord
|
115
|
+
include Sublet::Model
|
116
|
+
subletter(:company)
|
117
|
+
belongs_to :company
|
118
|
+
end
|
119
|
+
|
120
|
+
class Employee < ApplicationRecord
|
121
|
+
include Sublet::Model
|
122
|
+
subletter(:department)
|
123
|
+
belongs_to :department
|
124
|
+
end
|
125
|
+
```
|
126
|
+
|
127
|
+
#### Tenant Without Scoping
|
128
|
+
|
129
|
+
```ruby
|
130
|
+
class Company < ApplicationRecord
|
131
|
+
include Sublet::Model
|
132
|
+
sublet(scope: false) # Declare as tenant but don't auto-scope
|
133
|
+
end
|
134
|
+
```
|
135
|
+
|
136
|
+
### Validation
|
137
|
+
|
138
|
+
Sublet automatically validates that records belong to the current tenant:
|
139
|
+
|
140
|
+
```ruby
|
141
|
+
# This will fail validation if the employee doesn't belong to current_tenant
|
142
|
+
employee = Employee.new(department: wrong_department)
|
143
|
+
employee.valid? # => false
|
144
|
+
employee.errors[:base] # => ["Tenant mismatch"]
|
145
|
+
```
|
146
|
+
|
147
|
+
## Key Features
|
148
|
+
|
149
|
+
- **Hierarchy-aware**: Supports multi-level tenant hierarchies (Account → Company → Department → Employee)
|
150
|
+
- **Opt-in**: Only applies scoping where you explicitly set `current_tenant`
|
151
|
+
- **Fails open**: If tenant chain can't be resolved, no scoping is applied (safe default)
|
152
|
+
- **Automatic validation**: Prevents tenant mismatches during record creation/updates
|
153
|
+
- **Controller helpers**: Includes `set_current_sublet` helper method
|
154
|
+
- **Temporary switching**: `with_tenant` and `without_tenant` for temporary context changes
|
155
|
+
- **STI-safe**: Works correctly with Single Table Inheritance
|
156
|
+
|
157
|
+
## Development
|
158
|
+
|
159
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
160
|
+
|
161
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
162
|
+
|
163
|
+
## Contributing
|
164
|
+
|
165
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/gogrow-dev/sublet. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/gogrow-dev/sublet/blob/main/CODE_OF_CONDUCT.md).
|
166
|
+
|
167
|
+
## License
|
168
|
+
|
169
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
170
|
+
|
171
|
+
## Notes
|
172
|
+
|
173
|
+
- If a subletter chain can't be resolved to a tenant, Sublet **fails open** (no scoping).
|
174
|
+
- Tenants themselves are **not** scoped by default (use `sublet(scope: true)` to enable).
|
175
|
+
- The gem automatically includes controller helpers when Rails is present.
|
data/Rakefile
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Sublet
|
4
|
+
module ControllerHelpers
|
5
|
+
extend ActiveSupport::Concern
|
6
|
+
|
7
|
+
included do
|
8
|
+
helper_method :set_current_sublet if defined?(helper_method)
|
9
|
+
end
|
10
|
+
|
11
|
+
def set_current_sublet(tenant) # rubocop:disable Naming/AccessorMethodName
|
12
|
+
Sublet.current_tenant = tenant
|
13
|
+
end
|
14
|
+
end
|
15
|
+
end
|
data/lib/sublet/core.rb
ADDED
@@ -0,0 +1,121 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Sublet
|
4
|
+
module Core
|
5
|
+
module_function
|
6
|
+
|
7
|
+
# Build a scoped relation that limits +relation+ (for +model+) to the current tenant, if present.
|
8
|
+
def scoped_relation_for(model, relation = model.all)
|
9
|
+
tenant = Sublet.current_tenant
|
10
|
+
return relation unless tenant
|
11
|
+
|
12
|
+
path = Sublet::PathResolver.resolve_path_to_tenant(model)
|
13
|
+
return relation unless path && !path.empty? # fail-open if no path or tenant root not found
|
14
|
+
|
15
|
+
# Build deterministic INNER JOIN SQL across the whole chain to avoid AR 8 alias tracker issues
|
16
|
+
rel = relation
|
17
|
+
current_klass = model
|
18
|
+
current_table = current_klass.table_name
|
19
|
+
join_sql_parts = []
|
20
|
+
|
21
|
+
path.each do |assoc|
|
22
|
+
reflection = current_klass.reflect_on_association(assoc)
|
23
|
+
return relation unless reflection
|
24
|
+
|
25
|
+
next_klass = reflection.klass
|
26
|
+
next_table = next_klass.table_name
|
27
|
+
|
28
|
+
case reflection.macro
|
29
|
+
when :belongs_to
|
30
|
+
# current_table.fk = next_table.pk
|
31
|
+
fk = reflection.foreign_key
|
32
|
+
pk = reflection.association_primary_key
|
33
|
+
join_sql_parts << "INNER JOIN \"#{next_table}\" ON \"#{current_table}\".\"#{fk}\" = " \
|
34
|
+
"\"#{next_table}\".\"#{pk}\""
|
35
|
+
current_klass = next_klass
|
36
|
+
current_table = next_table
|
37
|
+
when :has_one, :has_many
|
38
|
+
# next_table.fk = current_table.pk
|
39
|
+
fk = reflection.foreign_key
|
40
|
+
pk = reflection.active_record_primary_key
|
41
|
+
join_sql_parts << "INNER JOIN \"#{next_table}\" ON \"#{next_table}\".\"#{fk}\" = " \
|
42
|
+
"\"#{current_table}\".\"#{pk}\""
|
43
|
+
current_klass = next_klass
|
44
|
+
current_table = next_table
|
45
|
+
else
|
46
|
+
# unsupported macro; fail open
|
47
|
+
return relation
|
48
|
+
end
|
49
|
+
end
|
50
|
+
|
51
|
+
rel = rel.joins(join_sql_parts.join(' ')) if join_sql_parts.any?
|
52
|
+
|
53
|
+
# Walk the path to discover the last klass we joined to
|
54
|
+
last_klass = model
|
55
|
+
path.each do |assoc|
|
56
|
+
reflection = last_klass.reflect_on_association(assoc)
|
57
|
+
return relation unless reflection
|
58
|
+
|
59
|
+
last_klass = reflection.klass
|
60
|
+
end
|
61
|
+
|
62
|
+
tenant_table = tenant.class.table_name
|
63
|
+
last_table = last_klass.table_name
|
64
|
+
|
65
|
+
# Case 1: the last hop IS the tenant class (e.g., ... -> Company)
|
66
|
+
return rel.where(tenant_table => { id: tenant.id }).distinct if last_klass == tenant.class
|
67
|
+
|
68
|
+
# Case 2: the last hop has a direct belongs_to to the tenant class
|
69
|
+
if (bt = last_klass.reflect_on_all_associations(:belongs_to).find { |r| r.klass == tenant.class })
|
70
|
+
return rel.where(last_table => { bt.foreign_key => tenant.id }).distinct
|
71
|
+
end
|
72
|
+
|
73
|
+
# Case 3: try a conventional association name matching the tenant class (e.g., :company)
|
74
|
+
assoc_name_guess = tenant.class.name.demodulize.underscore.to_sym
|
75
|
+
if last_klass.reflect_on_association(assoc_name_guess)
|
76
|
+
return rel.joins(assoc_name_guess).where(tenant_table => { id: tenant.id }).distinct
|
77
|
+
end
|
78
|
+
|
79
|
+
# Could not determine how to constrain; fail open
|
80
|
+
relation
|
81
|
+
end
|
82
|
+
|
83
|
+
# Build nested joins hash from an array of association names
|
84
|
+
# [:account, :company] => { account: :company }
|
85
|
+
# [:department] => :department
|
86
|
+
def build_nested_joins(joins_path)
|
87
|
+
return nil if joins_path.nil? || joins_path.empty?
|
88
|
+
|
89
|
+
joins_path.reverse.reduce(nil) { |acc, name| acc ? { name => acc } : name }
|
90
|
+
end
|
91
|
+
|
92
|
+
# Extract tenant id from a record instance by walking to the last hop and checking a FK or assoc.
|
93
|
+
def extract_tenant_id(record)
|
94
|
+
tenant = Sublet.current_tenant
|
95
|
+
return nil unless tenant
|
96
|
+
|
97
|
+
path = Sublet::PathResolver.resolve_path_to_tenant(record.class)
|
98
|
+
return nil unless path
|
99
|
+
|
100
|
+
obj = record
|
101
|
+
path.each do |assoc|
|
102
|
+
return nil unless obj.respond_to?(assoc)
|
103
|
+
|
104
|
+
obj = obj.public_send(assoc)
|
105
|
+
return nil if obj.nil?
|
106
|
+
end
|
107
|
+
|
108
|
+
if (bt = obj.class.reflect_on_all_associations(:belongs_to).find { |r| r.klass == tenant.class })
|
109
|
+
return obj.public_send(bt.foreign_key)
|
110
|
+
end
|
111
|
+
|
112
|
+
assoc_name_guess = tenant.class.name.demodulize.underscore
|
113
|
+
if obj.respond_to?(assoc_name_guess)
|
114
|
+
t = obj.public_send(assoc_name_guess)
|
115
|
+
return t&.id
|
116
|
+
end
|
117
|
+
|
118
|
+
nil
|
119
|
+
end
|
120
|
+
end
|
121
|
+
end
|
data/lib/sublet/model.rb
ADDED
@@ -0,0 +1,54 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Sublet
|
4
|
+
module Model
|
5
|
+
extend ActiveSupport::Concern
|
6
|
+
|
7
|
+
included do
|
8
|
+
class_attribute :_sublet_is_tenant, instance_accessor: false, default: false
|
9
|
+
class_attribute :_subletter_parent, instance_accessor: false, default: nil
|
10
|
+
end
|
11
|
+
|
12
|
+
class_methods do
|
13
|
+
# Tenant root. Pass scope: false to not autoscope the tenant table.
|
14
|
+
def sublet(scope: true)
|
15
|
+
self._sublet_is_tenant = true
|
16
|
+
return unless scope
|
17
|
+
|
18
|
+
klass = self # capture the model class for use inside the block
|
19
|
+
default_scope do
|
20
|
+
t = Sublet.current_tenant
|
21
|
+
if t.is_a?(klass) # STI-safe
|
22
|
+
where(id: t.id)
|
23
|
+
else
|
24
|
+
all
|
25
|
+
end
|
26
|
+
end
|
27
|
+
end
|
28
|
+
|
29
|
+
# Declare “sublet from” association (e.g., subletter(:department))
|
30
|
+
def subletter(parent_assoc_name)
|
31
|
+
self._subletter_parent = parent_assoc_name.to_sym
|
32
|
+
|
33
|
+
klass = self # capture the model class for use inside the block
|
34
|
+
default_scope do
|
35
|
+
Sublet::Core.scoped_relation_for(klass, all)
|
36
|
+
end
|
37
|
+
|
38
|
+
validate :_sublet_validate_alignment
|
39
|
+
end
|
40
|
+
end
|
41
|
+
|
42
|
+
private
|
43
|
+
|
44
|
+
def _sublet_validate_alignment
|
45
|
+
tenant = Sublet.current_tenant
|
46
|
+
return unless tenant
|
47
|
+
|
48
|
+
tid = Sublet::Core.extract_tenant_id(self)
|
49
|
+
return if tid.nil?
|
50
|
+
|
51
|
+
errors.add(:base, 'Tenant mismatch') unless tid == tenant.id
|
52
|
+
end
|
53
|
+
end
|
54
|
+
end
|
@@ -0,0 +1,37 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module Sublet
|
4
|
+
module PathResolver
|
5
|
+
module_function
|
6
|
+
|
7
|
+
# Walk from +klass+ following declared subletter parents until
|
8
|
+
# we find a tenant root (klass._sublet_is_tenant == true).
|
9
|
+
# Returns an array of association names (symbols), e.g. [:department, :company]
|
10
|
+
# or [] if +klass+ itself is the tenant root.
|
11
|
+
def resolve_path_to_tenant(klass)
|
12
|
+
path = []
|
13
|
+
current = klass
|
14
|
+
# prevent infinite loops
|
15
|
+
seen = {}
|
16
|
+
|
17
|
+
until current.nil? || current._sublet_is_tenant
|
18
|
+
return nil unless current.respond_to?(:_subletter_parent) # nothing declared
|
19
|
+
|
20
|
+
parent_assoc = current._subletter_parent
|
21
|
+
return nil if parent_assoc.nil?
|
22
|
+
return nil if seen[current] # cycle detected
|
23
|
+
|
24
|
+
seen[current] = true
|
25
|
+
|
26
|
+
path << parent_assoc
|
27
|
+
# Follow reflection to next klass
|
28
|
+
refl = current.reflect_on_association(parent_assoc)
|
29
|
+
return nil unless refl
|
30
|
+
|
31
|
+
current = refl.klass
|
32
|
+
end
|
33
|
+
|
34
|
+
current&._sublet_is_tenant ? path : nil
|
35
|
+
end
|
36
|
+
end
|
37
|
+
end
|
data/lib/sublet.rb
ADDED
@@ -0,0 +1,48 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require 'active_support'
|
4
|
+
require 'active_support/concern'
|
5
|
+
require 'active_support/current_attributes'
|
6
|
+
require 'active_record'
|
7
|
+
|
8
|
+
require 'sublet/version'
|
9
|
+
require 'sublet/current'
|
10
|
+
require 'sublet/path_resolver'
|
11
|
+
require 'sublet/core'
|
12
|
+
require 'sublet/model'
|
13
|
+
require 'sublet/controller_helpers'
|
14
|
+
|
15
|
+
# Auto-include controller helpers when Rails is present
|
16
|
+
if defined?(ActionController::Base)
|
17
|
+
ActiveSupport.on_load(:action_controller_base) do
|
18
|
+
include Sublet::ControllerHelpers
|
19
|
+
end
|
20
|
+
end
|
21
|
+
|
22
|
+
module Sublet
|
23
|
+
class << self
|
24
|
+
# Get the current tenant
|
25
|
+
def current_tenant
|
26
|
+
Current.tenant
|
27
|
+
end
|
28
|
+
|
29
|
+
# Set the current tenant
|
30
|
+
def current_tenant=(tenant)
|
31
|
+
Current.tenant = tenant
|
32
|
+
end
|
33
|
+
|
34
|
+
# Execute a block with a specific tenant, restoring the previous tenant afterward
|
35
|
+
def with_tenant(tenant)
|
36
|
+
prev = current_tenant
|
37
|
+
self.current_tenant = tenant
|
38
|
+
yield
|
39
|
+
ensure
|
40
|
+
self.current_tenant = prev
|
41
|
+
end
|
42
|
+
|
43
|
+
# Execute a block without any tenant context
|
44
|
+
def without_tenant(&)
|
45
|
+
with_tenant(nil, &)
|
46
|
+
end
|
47
|
+
end
|
48
|
+
end
|
data/sig/sublet.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,91 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: sublet
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Franco Pariani
|
8
|
+
bindir: exe
|
9
|
+
cert_chain: []
|
10
|
+
date: 2025-10-08 00:00:00.000000000 Z
|
11
|
+
dependencies:
|
12
|
+
- !ruby/object:Gem::Dependency
|
13
|
+
name: activerecord
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
15
|
+
requirements:
|
16
|
+
- - ">="
|
17
|
+
- !ruby/object:Gem::Version
|
18
|
+
version: '6.1'
|
19
|
+
type: :runtime
|
20
|
+
prerelease: false
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
22
|
+
requirements:
|
23
|
+
- - ">="
|
24
|
+
- !ruby/object:Gem::Version
|
25
|
+
version: '6.1'
|
26
|
+
- !ruby/object:Gem::Dependency
|
27
|
+
name: activesupport
|
28
|
+
requirement: !ruby/object:Gem::Requirement
|
29
|
+
requirements:
|
30
|
+
- - ">="
|
31
|
+
- !ruby/object:Gem::Version
|
32
|
+
version: '6.1'
|
33
|
+
type: :runtime
|
34
|
+
prerelease: false
|
35
|
+
version_requirements: !ruby/object:Gem::Requirement
|
36
|
+
requirements:
|
37
|
+
- - ">="
|
38
|
+
- !ruby/object:Gem::Version
|
39
|
+
version: '6.1'
|
40
|
+
description: Sublet lets you declare a tenant root and subletters that 'sublet from'
|
41
|
+
a parent association—even chaining through multiple levels. Developers set current_tenant
|
42
|
+
themselves in controllers; Sublet scopes AR queries automatically (including admin
|
43
|
+
filters) without adding tenant_id everywhere.
|
44
|
+
email:
|
45
|
+
- franco@gogrow.dev
|
46
|
+
executables: []
|
47
|
+
extensions: []
|
48
|
+
extra_rdoc_files: []
|
49
|
+
files:
|
50
|
+
- ".rspec"
|
51
|
+
- ".rubocop.yml"
|
52
|
+
- CHANGELOG.md
|
53
|
+
- CODE_OF_CONDUCT.md
|
54
|
+
- LICENSE.txt
|
55
|
+
- README.md
|
56
|
+
- Rakefile
|
57
|
+
- lib/sublet.rb
|
58
|
+
- lib/sublet/controller_helpers.rb
|
59
|
+
- lib/sublet/core.rb
|
60
|
+
- lib/sublet/current.rb
|
61
|
+
- lib/sublet/model.rb
|
62
|
+
- lib/sublet/path_resolver.rb
|
63
|
+
- lib/sublet/version.rb
|
64
|
+
- sig/sublet.rbs
|
65
|
+
homepage: https://github.com/gogrow-dev/sublet
|
66
|
+
licenses:
|
67
|
+
- MIT
|
68
|
+
metadata:
|
69
|
+
allowed_push_host: https://rubygems.org
|
70
|
+
homepage_uri: https://github.com/gogrow-dev/sublet
|
71
|
+
source_code_uri: https://github.com/gogrow-dev/sublet
|
72
|
+
changelog_uri: https://github.com/gogrow-dev/sublet/blob/main/CHANGELOG.md
|
73
|
+
rubygems_mfa_required: 'true'
|
74
|
+
rdoc_options: []
|
75
|
+
require_paths:
|
76
|
+
- lib
|
77
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
78
|
+
requirements:
|
79
|
+
- - ">="
|
80
|
+
- !ruby/object:Gem::Version
|
81
|
+
version: 3.1.0
|
82
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
83
|
+
requirements:
|
84
|
+
- - ">="
|
85
|
+
- !ruby/object:Gem::Version
|
86
|
+
version: '0'
|
87
|
+
requirements: []
|
88
|
+
rubygems_version: 3.6.2
|
89
|
+
specification_version: 4
|
90
|
+
summary: Hierarchy-aware, opt-in multi-tenancy scoping for ActiveRecord.
|
91
|
+
test_files: []
|