{"id":13395054,"url":"https://github.com/influitive/apartment","last_synced_at":"2025-05-13T18:14:44.731Z","repository":{"id":4814209,"uuid":"5967893","full_name":"influitive/apartment","owner":"influitive","description":"Database multi-tenancy for Rack (and Rails) applications","archived":false,"fork":false,"pushed_at":"2024-06-12T15:18:38.000Z","size":1269,"stargazers_count":2679,"open_issues_count":135,"forks_count":462,"subscribers_count":91,"default_branch":"development","last_synced_at":"2025-04-25T17:51:16.952Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"nathan7/binary-parse-stream","license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/influitive.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-09-26T15:28:36.000Z","updated_at":"2025-04-23T08:08:42.000Z","dependencies_parsed_at":"2024-05-01T10:35:50.342Z","dependency_job_id":"98c750cb-7fb0-4796-be8b-f53b13824582","html_url":"https://github.com/influitive/apartment","commit_stats":{"total_commits":581,"total_committers":108,"mean_commits":5.37962962962963,"dds":0.7246127366609294,"last_synced_commit":"f266f73e58835f94e4ec7c16f28443fe5eada1ac"},"previous_names":[],"tags_count":62,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influitive%2Fapartment","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influitive%2Fapartment/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influitive%2Fapartment/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/influitive%2Fapartment/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/influitive","download_url":"https://codeload.github.com/influitive/apartment/tar.gz/refs/heads/development","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254000885,"owners_count":21997443,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-30T17:01:40.548Z","updated_at":"2025-05-13T18:14:44.694Z","avatar_url":"https://github.com/influitive.png","language":"Ruby","readme":"# Apartment\n\n[![Gem Version](https://badge.fury.io/rb/apartment.svg)](https://badge.fury.io/rb/apartment)\n[![Code Climate](https://codeclimate.com/github/influitive/apartment/badges/gpa.svg)](https://codeclimate.com/github/influitive/apartment)\n[![Build Status](https://travis-ci.org/influitive/apartment.svg?branch=development)](https://travis-ci.org/influitive/apartment)\n\n*Multitenancy for Rails and ActiveRecord*\n\nApartment provides tools to help you deal with multiple tenants in your Rails\napplication. If you need to have certain data sequestered based on account or company,\nbut still allow some data to exist in a common tenant, Apartment can help.\n\n## HELP!\n\nIn order to help drive the direction of development and clean up the codebase, we'd like to take a poll\non how people are currently using Apartment. If you can take 5 seconds (1 question) to answer\nthis poll, we'd greatly appreciated it.\n\n[View Poll](http://www.poll-maker.com/poll391552x4Bfb41a9-15)\n\n## Excessive Memory Issues on ActiveRecord 4.x\n\n\u003e If you're noticing ever growing memory issues (ie growing with each tenant you add)\n\u003e when using Apartment, that's because there's [an issue](https://github.com/rails/rails/issues/19578)\n\u003e with how ActiveRecord maps Postgresql data types into AR data types.\n\u003e This has been patched and will be released for AR 4.2.2. It's apparently hard\n\u003e to backport to 4.1 unfortunately.\n\u003e If you're noticing high memory usage from ActiveRecord with Apartment please upgrade.\n\n```ruby\ngem 'rails', '4.2.1', github: 'influitive/rails', tag: 'v4.2.1.memfix'\n```\n\n## Installation\n\n### Rails\n\nAdd the following to your Gemfile:\n\n```ruby\ngem 'apartment'\n```\n\nThen generate your `Apartment` config file using\n\n```ruby\nbundle exec rails generate apartment:install\n```\n\nThis will create a `config/initializers/apartment.rb` initializer file.\nConfigure as needed using the docs below.\n\nThat's all you need to set up the Apartment libraries. If you want to switch tenants\non a per-user basis, look under \"Usage - Switching tenants per request\", below.\n\n\u003e NOTE: If using [postgresql schemas](http://www.postgresql.org/docs/9.0/static/ddl-schemas.html) you must use:\n\u003e\n\u003e * for Rails 3.1.x: _Rails ~\u003e 3.1.2_, it contains a [patch](https://github.com/rails/rails/pull/3232) that makes prepared statements work with multiple schemas\n\n## Usage\n\n### Video Tutorial\n\nHow to separate your application data into different accounts or companies.\n[GoRails #47](https://gorails.com/episodes/multitenancy-with-apartment)\n\n### Creating new Tenants\n\nBefore you can switch to a new apartment tenant, you will need to create it. Whenever\nyou need to create a new tenant, you can run the following command:\n\n```ruby\nApartment::Tenant.create('tenant_name')\n```\n\nIf you're using the [prepend environment](https://github.com/influitive/apartment#handling-environments) config option or you AREN'T using Postgresql Schemas, this will create a tenant in the following format: \"#{environment}\\_tenant_name\".\nIn the case of a sqlite database, this will be created in your 'db/' folder. With\nother databases, the tenant will be created as a new DB within the system.\n\nWhen you create a new tenant, all migrations will be run against that tenant, so it will be\nup to date when create returns.\n\n#### Notes on PostgreSQL\n\nPostgreSQL works slightly differently than other databases when creating a new tenant. If you\nare using PostgreSQL, Apartment by default will set up a new [schema](http://www.postgresql.org/docs/9.3/static/ddl-schemas.html)\nand migrate into there. This provides better performance, and allows Apartment to work on systems like Heroku, which\nwould not allow a full new database to be created.\n\nOne can optionally use the full database creation instead if they want, though this is not recommended\n\n### Switching Tenants\n\nTo switch tenants using Apartment, use the following command:\n\n```ruby\nApartment::Tenant.switch('tenant_name') do\n  # ...\nend\n```\n\nWhen switch is called, all requests coming to ActiveRecord will be routed to the tenant\nyou specify (with the exception of excluded models, see below). The tenant is automatically\nswitched back at the end of the block to what it was before.\n\nThere is also `switch!` which doesn't take a block, but it's recommended to use `switch`.\nTo return to the default tenant, you can call `switch` with no arguments.\n\n### Switching Tenants per request\n\nYou can have Apartment route to the appropriate tenant by adding some Rack middleware.\nApartment can support many different \"Elevators\" that can take care of this routing to your data.\n\n**NOTE: when switching tenants per-request, keep in mind that the order of your Rack middleware is important.**\nSee the [Middleware Considerations](#middleware-considerations) section for more.\n\nThe initializer above will generate the appropriate code for the Subdomain elevator\nby default. You can see this in `config/initializers/apartment.rb` after running\nthat generator. If you're *not* using the generator, you can specify your\nelevator below. Note that in this case you will **need** to require the elevator\nmanually in your `application.rb` like so\n\n```ruby\n# config/application.rb\nrequire 'apartment/elevators/subdomain' # or 'domain', 'first_subdomain', 'host'\n```\n\n#### Switch on subdomain\n\nIn house, we use the subdomain elevator, which analyzes the subdomain of the request and switches to a tenant schema of the same name. It can be used like so:\n\n```ruby\n# application.rb\nmodule MyApplication\n  class Application \u003c Rails::Application\n    config.middleware.use Apartment::Elevators::Subdomain\n  end\nend\n```\n\nIf you want to exclude a domain, for example if you don't want your application to treat www like a subdomain, in an initializer in your application, you can set the following:\n\n```ruby\n# config/initializers/apartment/subdomain_exclusions.rb\nApartment::Elevators::Subdomain.excluded_subdomains = ['www']\n```\n\nThis functions much in the same way as Apartment.excluded_models. This example will prevent switching your tenant when the subdomain is www. Handy for subdomains like: \"public\", \"www\", and \"admin\" :)\n\n#### Switch on first subdomain\n\nTo switch on the first subdomain, which analyzes the chain of subdomains of the request and switches to a tenant schema of the first name in the chain (e.g. owls.birds.animals.com would switch to \"owls\"). It can be used like so:\n\n```ruby\n# application.rb\nmodule MyApplication\n  class Application \u003c Rails::Application\n    config.middleware.use Apartment::Elevators::FirstSubdomain\n  end\nend\n```\n\nIf you want to exclude a domain, for example if you don't want your application to treat www like a subdomain, in an initializer in your application, you can set the following:\n\n```ruby\n# config/initializers/apartment/subdomain_exclusions.rb\nApartment::Elevators::FirstSubdomain.excluded_subdomains = ['www']\n```\n\nThis functions much in the same way as the Subdomain elevator. **NOTE:** in fact, at the time of this writing, the `Subdomain` and `FirstSubdomain` elevators both use the first subdomain ([#339](https://github.com/influitive/apartment/issues/339#issuecomment-235578610)). If you need to switch on larger parts of a Subdomain, consider using a Custom Elevator.\n\n#### Switch on domain\n\nTo switch based on full domain (excluding the 'www' subdomains and top level domains *ie '.com'* ) use the following:\n\n```ruby\n# application.rb\nmodule MyApplication\n  class Application \u003c Rails::Application\n    config.middleware.use Apartment::Elevators::Domain\n  end\nend\n```\n\nNote that if you have several subdomains, then it will match on the first *non-www* subdomain:\n- example.com =\u003e example\n- www.example.com =\u003e example\n- a.example.com =\u003e a\n\n#### Switch on full host using a hash\n\nTo switch based on full host with a hash to find corresponding tenant name use the following:\n\n```ruby\n# application.rb\nmodule MyApplication\n  class Application \u003c Rails::Application\n    config.middleware.use Apartment::Elevators::HostHash, {'example.com' =\u003e 'example_tenant'}\n  end\nend\n```\n\n#### Switch on full host, ignoring given first subdomains\n\nTo switch based on full host to find corresponding tenant name use the following:\n\n```ruby\n# application.rb\nmodule MyApplication\n  class Application \u003c Rails::Application\n    config.middleware.use Apartment::Elevators::Host\n  end\nend\n```\n\nIf you want to exclude a first-subdomain, for example if you don't want your application to include www in the matching, in an initializer in your application, you can set the following:\n\n```ruby\nApartment::Elevators::Host.ignored_first_subdomains = ['www']\n```\n\nWith the above set, these would be the results:\n- example.com =\u003e example.com\n- www.example.com =\u003e example.com\n- a.example.com =\u003e a.example.com\n- www.a.example.com =\u003e a.example.com\n\n#### Custom Elevator\n\nA Generic Elevator exists that allows you to pass a `Proc` (or anything that responds to `call`) to the middleware. This Object will be passed in an `ActionDispatch::Request` object when called for you to do your magic. Apartment will use the return value of this proc to switch to the appropriate tenant. Use like so:\n\n```ruby\n# application.rb\nmodule MyApplication\n  class Application \u003c Rails::Application\n    # Obviously not a contrived example\n    config.middleware.use Apartment::Elevators::Generic, Proc.new { |request| request.host.reverse }\n  end\nend\n```\n\nYour other option is to subclass the Generic elevator and implement your own\nswitching mechanism. This is exactly how the other elevators work. Look at\nthe `subdomain.rb` elevator to get an idea of how this should work. Basically\nall you need to do is subclass the generic elevator and implement your own\n`parse_tenant_name` method that will ultimately return the name of the tenant\nbased on the request being made. It *could* look something like this:\n\n```ruby\n# app/middleware/my_custom_elevator.rb\nclass MyCustomElevator \u003c Apartment::Elevators::Generic\n\n  # @return {String} - The tenant to switch to\n  def parse_tenant_name(request)\n    # request is an instance of Rack::Request\n\n    # example: look up some tenant from the db based on this request\n    tenant_name = SomeModel.from_request(request)\n\n    return tenant_name\n  end\nend\n```\n\n#### Middleware Considerations\n\nIn the examples above, we show the Apartment middleware being appended to the Rack stack with\n\n```ruby\nRails.application.config.middleware.use Apartment::Elevators::Subdomain\n```\n\nBy default, the Subdomain middleware switches into a Tenant based on the subdomain at the beginning of the request, and when the request is finished, it switches back to the \"public\" Tenant. This happens in the [Generic](https://github.com/influitive/apartment/blob/development/lib/apartment/elevators/generic.rb#L22) elevator, so all elevators that inherit from this elevator will operate as such.\n\nIt's also good to note that Apartment switches back to the \"public\" tenant any time an error is raised in your application.\n\nThis works okay for simple applications, but it's important to consider that you may want to maintain the \"selected\" tenant through different parts of the Rack application stack. For example, the [Devise](https://github.com/plataformatec/devise) gem adds the `Warden::Manager` middleware at the end of the stack in the examples above, our `Apartment::Elevators::Subdomain` middleware would come after it. Trouble is, Apartment resets the selected tenant after the request is finish, so some redirects (e.g. authentication) in Devise will be run in the context of the \"public\" tenant. The same issue would also effect a gem such as the [better_errors](https://github.com/charliesome/better_errors) gem which inserts a middleware quite early in the Rails middleware stack.\n\nTo resolve this issue, consider adding the Apartment middleware at a location in the Rack stack that makes sense for your needs, e.g.:\n\n```ruby\nRails.application.config.middleware.insert_before Warden::Manager, Apartment::Elevators::Subdomain\n```\n\nNow work done in the Warden middleware is wrapped in the `Apartment::Tenant.switch` context started in the Generic elevator.\n\n### Dropping Tenants\n\nTo drop tenants using Apartment, use the following command:\n\n```ruby\nApartment::Tenant.drop('tenant_name')\n```\n\nWhen method is called, the schema is dropped and all data from itself will be lost. Be careful with this method.\n\n## Config\n\nThe following config options should be set up in a Rails initializer such as:\n\n    config/initializers/apartment.rb\n\nTo set config options, add this to your initializer:\n\n```ruby\nApartment.configure do |config|\n  # set your options (described below) here\nend\n```\n\n### Excluding models\n\nIf you have some models that should always access the 'public' tenant, you can specify this by configuring Apartment using `Apartment.configure`. This will yield a config object for you. You can set excluded models like so:\n\n```ruby\nconfig.excluded_models = [\"User\", \"Company\"]        # these models will not be multi-tenanted, but remain in the global (public) namespace\n```\n\nNote that a string representation of the model name is now the standard so that models are properly constantized when reloaded in development\n\nRails will always access the 'public' tenant when accessing these models, but note that tables will be created in all schemas. This may not be ideal, but its done this way because otherwise rails wouldn't be able to properly generate the schema.rb file.\n\n\u003e **NOTE - Many-To-Many Excluded Models:**\n\u003e Since model exclusions must come from referencing a real ActiveRecord model, `has_and_belongs_to_many` is NOT supported. In order to achieve a many-to-many relationship for excluded models, you MUST use `has_many :through`. This way you can reference the join model in the excluded models configuration.\n\n### Postgresql Schemas\n\n## Providing a Different default_schema\n\nBy default, ActiveRecord will use `\"$user\", public` as the default `schema_search_path`. This can be modified if you wish to use a different default schema be setting:\n\n```ruby\nconfig.default_schema = \"some_other_schema\"\n```\n\nWith that set, all excluded models will use this schema as the table name prefix instead of `public` and `reset` on `Apartment::Tenant` will return to this schema as well.\n\n## Persistent Schemas\n\nApartment will normally just switch the `schema_search_path` whole hog to the one passed in. This can lead to problems if you want other schemas to always be searched as well. Enter `persistent_schemas`. You can configure a list of other schemas that will always remain in the search path, while the default gets swapped out:\n\n```ruby\nconfig.persistent_schemas = ['some', 'other', 'schemas']\n```\n\n### Installing Extensions into Persistent Schemas\n\nPersistent Schemas have numerous useful applications.  [Hstore](http://www.postgresql.org/docs/9.1/static/hstore.html), for instance, is a popular storage engine for Postgresql. In order to use extensions such as Hstore, you have to install it to a specific schema and have that always in the `schema_search_path`.\n\nWhen using extensions, keep in mind:\n* Extensions can only be installed into one schema per database, so we will want to install it into a schema that is always available in the `schema_search_path`\n* The schema and extension need to be created in the database *before* they are referenced in migrations, database.yml or apartment.\n* There does not seem to be a way to create the schema and extension using standard rails migrations.\n* Rails db:test:prepare deletes and recreates the database, so it needs to be easy for the extension schema to be recreated here.\n\n#### 1. Ensure the extensions schema is created when the database is created\n\n```ruby\n# lib/tasks/db_enhancements.rake\n\n####### Important information ####################\n# This file is used to setup a shared extensions #\n# within a dedicated schema. This gives us the   #\n# advantage of only needing to enable extensions #\n# in one place.                                  #\n#                                                #\n# This task should be run AFTER db:create but    #\n# BEFORE db:migrate.                             #\n##################################################\n\nnamespace :db do\n  desc 'Also create shared_extensions Schema'\n  task :extensions =\u003e :environment  do\n    # Create Schema\n    ActiveRecord::Base.connection.execute 'CREATE SCHEMA IF NOT EXISTS shared_extensions;'\n    # Enable Hstore\n    ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS HSTORE SCHEMA shared_extensions;'\n    # Enable UUID-OSSP\n    ActiveRecord::Base.connection.execute 'CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\" SCHEMA shared_extensions;'\n    # Grant usage to public\n    ActiveRecord::Base.connection.execute 'GRANT usage ON SCHEMA shared_extensions to public;'\n  end\nend\n\nRake::Task[\"db:create\"].enhance do\n  Rake::Task[\"db:extensions\"].invoke\nend\n\nRake::Task[\"db:test:purge\"].enhance do\n  Rake::Task[\"db:extensions\"].invoke\nend\n```\n\n#### 2. Ensure the schema is in Rails' default connection\n\nNext, your `database.yml` file must mimic what you've set for your default and persistent schemas in Apartment. When you run migrations with Rails, it won't know about the extensions schema because Apartment isn't injected into the default connection, it's done on a per-request basis, therefore Rails doesn't know about `hstore` or `uuid-ossp` during migrations.  To do so, add the following to your `database.yml` for all environments\n\n```yaml\n# database.yml\n...\nadapter: postgresql\nschema_search_path: \"public,shared_extensions\"\n...\n```\n\nThis would be for a config with `default_schema` set to `public` and `persistent_schemas` set to `['shared_extensions']`. **Note**: This only works on Heroku with [Rails 4.1+](https://devcenter.heroku.com/changelog-items/426). For apps that use older Rails versions hosted on Heroku, the only way to properly setup is to start with a fresh PostgreSQL instance:\n\n1. Append `?schema_search_path=public,hstore` to your `DATABASE_URL` environment variable, by this you don't have to revise the `database.yml` file (which is impossible since Heroku regenerates a completely different and immutable `database.yml` of its own on each deploy)\n2. Run `heroku pg:psql` from your command line\n3. And then `DROP EXTENSION hstore;` (**Note:** This will drop all columns that use `hstore` type, so proceed with caution; only do this with a fresh PostgreSQL instance)\n4. Next: `CREATE SCHEMA IF NOT EXISTS hstore;`\n5. Finally: `CREATE EXTENSION IF NOT EXISTS hstore SCHEMA hstore;` and hit enter (`\\q` to exit)\n\nTo double check, login to the console of your Heroku app and see if `Apartment.connection.schema_search_path` is `public,hstore`\n\n#### 3. Ensure the schema is in the apartment config\n\n```ruby\n# config/initializers/apartment.rb\n...\nconfig.persistent_schemas = ['shared_extensions']\n...\n```\n\n#### Alternative: Creating schema by default\n\nAnother way that we've successfully configured hstore for our applications is to add it into the\npostgresql template1 database so that every tenant that gets created has it by default.\n\nOne caveat with this approach is that it can interfere with other projects in development using the same extensions and template, but not using apartment with this approach.\n\nYou can do so using a command like so\n\n```bash\npsql -U postgres -d template1 -c \"CREATE SCHEMA shared_extensions AUTHORIZATION some_username;\"\npsql -U postgres -d template1 -c \"CREATE EXTENSION IF NOT EXISTS hstore SCHEMA shared_extensions;\"\n```\n\nThe *ideal* setup would actually be to install `hstore` into the `public` schema and leave the public\nschema in the `search_path` at all times. We won't be able to do this though until public doesn't\nalso contain the tenanted tables, which is an open issue with no real milestone to be completed.\nHappy to accept PR's on the matter.\n\n#### Alternative: Creating new schemas by using raw SQL dumps\n\nApartment can be forced to use raw SQL dumps insted of `schema.rb` for creating new schemas. Use this when you are using some extra features in postgres that can't be represented in `schema.rb`, like materialized views etc.\n\nThis only applies while using postgres adapter and `config.use_schemas` is set to `true`.\n(Note: this option doesn't use `db/structure.sql`, it creates SQL dump by executing `pg_dump`)\n\nEnable this option with:\n```ruby\nconfig.use_sql = true\n```\n\n### Managing Migrations\n\nIn order to migrate all of your tenants (or postgresql schemas) you need to provide a list\nof dbs to Apartment. You can make this dynamic by providing a Proc object to be called on migrations.\nThis object should yield an array of string representing each tenant name. Example:\n\n```ruby\n# Dynamically get tenant names to migrate\nconfig.tenant_names = lambda{ Customer.pluck(:tenant_name) }\n\n# Use a static list of tenant names for migrate\nconfig.tenant_names = ['tenant1', 'tenant2']\n```\n\nYou can then migrate your tenants using the normal rake task:\n\n```ruby\nrake db:migrate\n```\n\nThis just invokes `Apartment::Tenant.migrate(#{tenant_name})` for each tenant name supplied\nfrom `Apartment.tenant_names`\n\nNote that you can disable the default migrating of all tenants with `db:migrate` by setting\n`Apartment.db_migrate_tenants = false` in your `Rakefile`. Note this must be done\n*before* the rake tasks are loaded. ie. before `YourApp::Application.load_tasks` is called\n\n#### Parallel Migrations\n\nApartment supports parallelizing migrations into multiple threads when\nyou have a large number of tenants. By default, parallel migrations is\nturned off. You can enable this by setting `parallel_migration_threads` to \nthe number of threads you want to use in your initializer.\n\nKeep in mind that because migrations are going to access the database,\nthe number of threads indicated here should be less than the pool size\nthat Rails will use to connect to your database.\n\n### Handling Environments\n\nBy default, when not using postgresql schemas, Apartment will prepend the environment to the tenant name\nto ensure there is no conflict between your environments. This is mainly for the benefit of your development\nand test environments. If you wish to turn this option off in production, you could do something like:\n\n```ruby\nconfig.prepend_environment = !Rails.env.production?\n```\n\n## Tenants on different servers\n\nYou can store your tenants in different databases on one or more servers.\nTo do it, specify your `tenant_names` as a hash, keys being the actual tenant names,\nvalues being a hash with the database configuration to use.\n\nExample:\n\n```ruby\nconfig.with_multi_server_setup = true\nconfig.tenant_names = {\n  'tenant1' =\u003e {\n    adapter: 'postgresql',\n    host: 'some_server',\n    port: 5555,\n    database: 'postgres' # this is not the name of the tenant's db\n                         # but the name of the database to connect to, before creating the tenant's db\n                         # mandatory in postgresql\n  }\n}\n# or using a lambda:\nconfig.tenant_names = lambda do\n  Tenant.all.each_with_object({}) do |tenant, hash|\n    hash[tenant.name] = tenant.db_configuration\n  end\nend\n```\n\n## Background workers\n\nSee [apartment-sidekiq](https://github.com/influitive/apartment-sidekiq) or [apartment-activejob](https://github.com/influitive/apartment-activejob).\n\n## Callbacks\n\nYou can execute callbacks when switching between tenants or creating a new one, Apartment provides the following callbacks:\n\n- before_create\n- after_create\n- before_switch\n- after_switch\n\nYou can register a callback using [ActiveSupport::Callbacks](https://api.rubyonrails.org/classes/ActiveSupport/Callbacks.html) the following way:\n\n```ruby\nrequire 'apartment/adapters/abstract_adapter'\n\nmodule Apartment\n  module Adapters\n    class AbstractAdapter\n      set_callback :switch, :before do |object|\n        ...\n      end\n    end\n  end\nend\n```\n\n## Contributing\n\n* In both `spec/dummy/config` and `spec/config`, you will see `database.yml.sample` files\n  * Copy them into the same directory but with the name `database.yml`\n  * Edit them to fit your own settings\n* Rake tasks (see the Rakefile) will help you setup your dbs necessary to run tests\n* Please issue pull requests to the `development` branch. All development happens here, master is used for releases.\n* Ensure that your code is accompanied with tests. No code will be merged without tests\n\n* If you're looking to help, check out the TODO file for some upcoming changes I'd like to implement in Apartment.\n\n## License\n\nApartment is released under the [MIT License](http://www.opensource.org/licenses/MIT).\n","funding_links":[],"categories":["Web Apps, Services \u0026 Interaction","Uncategorized","ORM/ODM Extensions","Ruby","Multi-tenancy","Helpers and Tools"],"sub_categories":["Multitenancy","Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finfluitive%2Fapartment","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Finfluitive%2Fapartment","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Finfluitive%2Fapartment/lists"}