From 5f8db67cc02250af4a8896fa47bd48731cbf5540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Javi=20Mart=C3=ADn?= Date: Fri, 29 Mar 2024 02:34:45 +0100 Subject: [PATCH] Make Apartment compatible with Rails 7 The `database:` argument from the `connected_to` method was deprecated in Rails 6.1 [1] and removed in Rails 7.0 [2]. The ros-apartement gem has already introduced fixes for this issue [3][4], but there has been no release including these fixes. So we're applying the fix in our code. Note that, since Apartment already overwrites the `connected_to` method by creating a `connected_to_with_tenant` method, we're calling the `connected_to_without_tenant` method inside the patch, which is equivalent to ActiveRecord's original `connected_to`. [1] Pull request 37874 in https://github.com/rails/rails [2] Pull request 40530 in https://github.com/rails/rails/pull [3] Pull request 194 in https://github.com/rails-on-services/apartment [4] Pull request 243 in https://github.com/rails-on-services/apartment --- Gemfile | 2 +- config/initializers/apartment.rb | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 7514d7801..82f6831d6 100644 --- a/Gemfile +++ b/Gemfile @@ -46,7 +46,7 @@ gem "recipient_interceptor", "~> 0.3.1" gem "redcarpet", "~> 3.6.0" gem "responders", "~> 3.1.1" gem "rinku", "~> 2.0.6", require: "rails_rinku" -gem "ros-apartment", "~> 2.11.0", require: "apartment" +gem "ros-apartment", "~> 2.11.0", require: "apartment" # Remove ConnectionHandling monkey patch when upgrading gem "sassc-embedded", "~> 1.70.1" gem "sassc-rails", "~> 2.1.2" gem "savon", "~> 2.15.0" diff --git a/config/initializers/apartment.rb b/config/initializers/apartment.rb index cda7ae581..e5d0a5110 100644 --- a/config/initializers/apartment.rb +++ b/config/initializers/apartment.rb @@ -1,3 +1,20 @@ +module ActiveRecord # TODO: Remove after upgrading ros-apartment + # Code based on the current (as of March 2024) development version of the apartment gem + module ConnectionHandling + def connected_to_with_rails7_tenant(role: nil, prevent_writes: false, &blk) + current_tenant = Apartment::Tenant.current + + # The connected_to_without_tenant method is defined by Apartment + connected_to_without_tenant(role: role, prevent_writes: prevent_writes) do + Apartment::Tenant.switch!(current_tenant) + yield(blk) + end + end + + alias connected_to connected_to_with_rails7_tenant + end +end + # You can have Apartment route to the appropriate Tenant by adding some Rack middleware. # Apartment can support many different "Elevators" that can take care of this routing to your data. # Require whichever Elevator you're using below or none if you have a custom one.