multi_tenant_subdomain 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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0e0dbab0670afbd0e9ec60de68b40fb3021a6f23c489e7065d64200194d5051e
4
+ data.tar.gz: e1aa495aabba98159e312e16364398627b199bb8197a5e734e62e867c92dfce7
5
+ SHA512:
6
+ metadata.gz: 431d99f799cc6870052617bb287a58f8c1c935bfb46c846bda3398b32971e4fb6990fb7feb3bedc9f1cc1ed576cb58da143fd0050d2f22101242fb1d92c6718e
7
+ data.tar.gz: e8eabe2cb7de0ea0e4cdd609027fbcca5acac8f3416367cabbfb0683e5a5b253ffd0c2f48d5b5509cf1397eb02fd15445e15d188220a5f3aa1b55955d74e1b78
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,8 @@
1
+ AllCops:
2
+ TargetRubyVersion: 3.1
3
+
4
+ Style/StringLiterals:
5
+ EnforcedStyle: double_quotes
6
+
7
+ Style/StringLiteralsInInterpolation:
8
+ EnforcedStyle: double_quotes
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-02-24
4
+
5
+ - Initial release
@@ -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 Sharvy Ahmed
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,51 @@
1
+ # MultiTenantSubdomain
2
+
3
+ A gem that provides subdomain-based multi-tenancy support for Rails applications, using a single database while ensuring tenant isolation.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem "multi_tenant_subdomain"
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ ```bash
16
+ bundle install
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ 1. **Generate the tenant model:**
22
+
23
+ ```bash
24
+ rails generate multi_tenant_subdomain YourTenantModel
25
+ ```
26
+
27
+ Replace `YourTenantModel` with the actual name of your tenant model (e.g., `Account`, `Organization`). This generator will:
28
+
29
+ - Create a model (if it doesn't exist) with a `subdomain` attribute.
30
+ - Add a migration to add the `subdomain` column to the model's table (if the table exists and the column is missing).
31
+ - Create an initializer to configure the `tenant_model`.
32
+
33
+ 2. **Configure the tenant model:**
34
+
35
+ The generator creates an initializer file `config/initializers/multi_tenant_subdomain.rb` with the following content:
36
+
37
+ ```ruby
38
+ MultiTenantSubdomain.configure do |config|
39
+ config.tenant_model = "YourTenantModel"
40
+ end
41
+ ```
42
+
43
+ Ensure `YourTenantModel` matches the name of your tenant model.
44
+
45
+ ## Contributing
46
+
47
+ Bug reports and pull requests are welcome on [GitHub](https://github.com/sharvy/multi_tenant_subdomain).
48
+
49
+ ## License
50
+
51
+ The gem is available as open source under the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,105 @@
1
+ require "rails/generators"
2
+ require "active_record"
3
+ require "fileutils"
4
+
5
+ module MultiTenantSubdomain
6
+ class MultiTenantSubdomainGenerator < Rails::Generators::Base
7
+ source_root File.expand_path("templates", __dir__)
8
+ argument :model_name, type: :string
9
+
10
+ def create_model
11
+ return if behavior != :invoke
12
+
13
+ unless model_exists?
14
+ generate "model", "#{model_name} subdomain:string:index"
15
+ else
16
+ add_subdomain_field if migration_needed?
17
+ end
18
+
19
+ create_initializer
20
+ end
21
+
22
+ def destroy
23
+ return if behavior != :revoke
24
+ remove_initializer
25
+ remove_model if model_exists?
26
+ remove_migrations
27
+ end
28
+
29
+ private
30
+
31
+ def model_exists?
32
+ File.exist?(Rails.root.join("app", "models", "#{model_name.underscore}.rb"))
33
+ end
34
+
35
+ def table_exists?
36
+ ActiveRecord::Base.connection.data_source_exists?(model_name.tableize)
37
+ end
38
+
39
+ def column_exists?(column)
40
+ return false unless table_exists?
41
+
42
+ ActiveRecord::Base.connection.column_exists?(model_name.tableize, column)
43
+ end
44
+
45
+ def migration_needed?
46
+ table_exists? && !column_exists?(:subdomain)
47
+ end
48
+
49
+ def add_subdomain_field
50
+ timestamp = Time.now.strftime("%Y%m%d%H%M%S")
51
+ migration_file = "db/migrate/#{timestamp}_add_subdomain_to_#{model_name.tableize}.rb"
52
+
53
+ create_file migration_file, <<~RUBY
54
+ class AddSubdomainTo#{model_name.camelize} < ActiveRecord::Migration[#{Rails.version.to_f}]
55
+ def change
56
+ add_column :#{model_name.tableize}, :subdomain, :string, index: true
57
+ end
58
+ end
59
+ RUBY
60
+ end
61
+
62
+ def create_initializer
63
+ initializer_path = Rails.root.join("config", "initializers", "multi_tenant_subdomain.rb")
64
+
65
+ unless File.exist?(initializer_path)
66
+ create_file initializer_path, <<~RUBY
67
+ MultiTenantSubdomain.configure do |config|
68
+ config.tenant_model = #{model_name.to_s.camelize}
69
+ end
70
+ RUBY
71
+ else
72
+ puts "X Initializer already exists. Skipping..."
73
+ end
74
+ end
75
+
76
+ def remove_initializer
77
+ initializer_path = Rails.root.join("config", "initializers", "multi_tenant_subdomain.rb")
78
+ if File.exist?(initializer_path)
79
+ FileUtils.rm_f(initializer_path)
80
+ puts "X Removed initializer: config/initializers/multi_tenant_subdomain.rb"
81
+ end
82
+ end
83
+
84
+ def remove_model
85
+ model_path = Rails.root.join("app", "models", "#{model_name.underscore}.rb")
86
+ test_path = Rails.root.join("test", "models", "#{model_name.underscore}_test.rb")
87
+ spec_path = Rails.root.join("spec", "models", "#{model_name.underscore}_spec.rb")
88
+
89
+ [model_path, test_path, spec_path].each do |path|
90
+ FileUtils.rm_f(path) if File.exist?(path)
91
+ end
92
+
93
+ puts "X Removed model: #{model_name}"
94
+ end
95
+
96
+ def remove_migrations
97
+ migration_files = Dir.glob(Rails.root.join("db", "migrate", "*_#{model_name.tableize}.rb"))
98
+ migration_files.each do |file|
99
+ FileUtils.rm_f(file) if File.exist?(file)
100
+ end
101
+
102
+ puts "X Removed migrations related to #{model_name}"
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,18 @@
1
+ module MultiTenantSubdomain
2
+ module ActiveRecordExtension
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ default_scope { where(tenant_id: MultiTenantSubdomain::TenantManager.current_tenant&.id) }
7
+ before_validation :set_tenant_id
8
+ end
9
+
10
+ private
11
+
12
+ def set_tenant_id
13
+ self.tenant_id = MultiTenantSubdomain::TenantManager.current_tenant&.id
14
+ end
15
+ end
16
+ end
17
+
18
+ ActiveRecord::Base.include MultiTenantSubdomain::ActiveRecordExtension
@@ -0,0 +1,32 @@
1
+ module MultiTenantSubdomain
2
+ class Middleware
3
+ def initialize(app)
4
+ @app = app
5
+ end
6
+
7
+ def call(env)
8
+ tenant = extract_subdomain(env)
9
+ MultiTenantSubdomain::TenantManager.current_tenant = tenant
10
+ @app.call(env)
11
+ ensure
12
+ # IMPORTANT: Reset the tenant after the request is processed
13
+ # This ensures that the tenant is not shared between requests
14
+ MultiTenantSubdomain::TenantManager.reset_tenant
15
+ end
16
+
17
+ private
18
+
19
+ def extract_subdomain(env)
20
+ request = Rack::Request.new(env)
21
+ host_parts = request.host.split('.')
22
+
23
+ # Avoid affecting primary domain
24
+ return nil if host_parts.length < 3
25
+
26
+ # Avoid affecting www subdomain
27
+ return nil if host_parts.first == 'www'
28
+
29
+ host_parts.first
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,7 @@
1
+ module MultiTenantSubdomain
2
+ class Railtie < Rails::Railtie
3
+ initializer "multi_tenant_subdomain.configure_rails_initialization" do |app|
4
+ app.middleware.use MultiTenantSubdomain::Middleware
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,19 @@
1
+ module MultiTenantSubdomain
2
+ class TenantManager
3
+ MTS_KEY = :current_tenant
4
+
5
+ class << self
6
+ def current_tenant
7
+ Thread.current[MTS_KEY]
8
+ end
9
+
10
+ def current_tenant=(tenant)
11
+ Thread.current[MTS_KEY] = tenant
12
+ end
13
+
14
+ def reset_tenant
15
+ Thread.current[MTS_KEY] = nil
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module MultiTenantSubdomain
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "multi_tenant_subdomain/version"
4
+ require_relative "multi_tenant_subdomain/railtie"
5
+ require_relative "multi_tenant_subdomain/tenant_manager"
6
+ require_relative "multi_tenant_subdomain/middleware"
7
+ require_relative "multi_tenant_subdomain/active_record_extension"
8
+ require_relative "generators/multi_tenant_subdomain/multi_tenant_subdomain_generator"
9
+
10
+ module MultiTenantSubdomain
11
+ class Error < StandardError; end
12
+ class << self
13
+ attr_accessor :config
14
+
15
+ def configure
16
+ self.config ||= Configuration.new
17
+ yield(config) if block_given?
18
+ end
19
+ end
20
+ class Configuration
21
+ attr_accessor :tenant_model
22
+
23
+ def initialize
24
+ @tenant_model = "Tenant"
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,4 @@
1
+ module MultiTenantSubdomain
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,117 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: multi_tenant_subdomain
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sharvy Ahmed
8
+ bindir: exe
9
+ cert_chain: []
10
+ date: 2025-02-24 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: rspec
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '0'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - ">="
24
+ - !ruby/object:Gem::Version
25
+ version: '0'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rubocop
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '0'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: '0'
40
+ - !ruby/object:Gem::Dependency
41
+ name: bundler
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ - !ruby/object:Gem::Dependency
55
+ name: rake
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: '0'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ description: This gem provides subdomain-based multi-tenancy support for Rails applications,
69
+ using a single database while ensuring tenant isolation.
70
+ email:
71
+ - sharvy2008@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".rspec"
77
+ - ".rubocop.yml"
78
+ - CHANGELOG.md
79
+ - CODE_OF_CONDUCT.md
80
+ - LICENSE.txt
81
+ - README.md
82
+ - Rakefile
83
+ - lib/generators/multi_tenant_subdomain/multi_tenant_subdomain_generator.rb
84
+ - lib/multi_tenant_subdomain.rb
85
+ - lib/multi_tenant_subdomain/active_record_extension.rb
86
+ - lib/multi_tenant_subdomain/middleware.rb
87
+ - lib/multi_tenant_subdomain/railtie.rb
88
+ - lib/multi_tenant_subdomain/tenant_manager.rb
89
+ - lib/multi_tenant_subdomain/version.rb
90
+ - sig/multi_tenant_subdomain.rbs
91
+ homepage: https://github.com/sharvy/multi_tenant_subdomain
92
+ licenses:
93
+ - MIT
94
+ metadata:
95
+ allowed_push_host: https://rubygems.org
96
+ homepage_uri: https://github.com/sharvy/multi_tenant_subdomain
97
+ source_code_uri: https://github.com/sharvy/multi_tenant_subdomain
98
+ changelog_uri: https://github.com/sharvy/multi_tenant_subdomain/blob/main/CHANGELOG.md
99
+ rdoc_options: []
100
+ require_paths:
101
+ - lib
102
+ required_ruby_version: !ruby/object:Gem::Requirement
103
+ requirements:
104
+ - - ">="
105
+ - !ruby/object:Gem::Version
106
+ version: 3.1.0
107
+ required_rubygems_version: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - ">="
110
+ - !ruby/object:Gem::Version
111
+ version: '0'
112
+ requirements: []
113
+ rubygems_version: 3.6.3
114
+ specification_version: 4
115
+ summary: Multi-tenancy support with subdomain-based tenant isolation using a single
116
+ database.
117
+ test_files: []