Extract method to get the tenant root storage

This way we simplify the code a little bit and we create a method unique
to the `TenantDiskService` class, which can be used to check whether
we're using this class without using `is_a?` or similar.
This commit is contained in:
Javi Martín
2024-04-15 20:13:04 +02:00
parent faf765b5c6
commit ce7acbbff7
3 changed files with 32 additions and 6 deletions

View File

@@ -2,11 +2,19 @@ require "active_storage/service/disk_service"
module ActiveStorage
class Service::TenantDiskService < Service::DiskService
def tenant_root
File.join(root, Tenant.subfolder_path)
end
def tenant_root_for(...)
File.join(root, Tenant.subfolder_path_for(...))
end
def path_for(key)
if Tenant.default?
super
else
super.sub(root, File.join(root, Tenant.subfolder_path))
super.sub(root, tenant_root)
end
end
end

View File

@@ -112,10 +112,14 @@ class Tenant < ApplicationRecord
end
def self.subfolder_path
if default?
subfolder_path_for(current_schema)
end
def self.subfolder_path_for(schema)
if schema == "public"
""
else
File.join("tenants", current_schema)
File.join("tenants", schema)
end
end
@@ -178,12 +182,15 @@ class Tenant < ApplicationRecord
end
def rename_storage
return unless ActiveStorage::Blob.service.is_a?(ActiveStorage::Service::TenantDiskService)
service = ActiveStorage::Blob.service
return unless service.is_a?(ActiveStorage::Service::TenantDiskService)
old_storage = service.tenant_root_for(schema_before_last_save)
old_storage = File.join(ActiveStorage::Blob.service.root, "tenants", schema_before_last_save)
return unless File.directory?(old_storage)
new_storage = File.join(ActiveStorage::Blob.service.root, "tenants", schema)
new_storage = service.tenant_root_for(schema)
File.rename(old_storage, new_storage)
end

View File

@@ -0,0 +1,11 @@
require "rails_helper"
describe ActiveStorage::Service::TenantDiskService do
describe "#tenant_root_for" do
it "returns the folder of the given tenant" do
service = ActiveStorage::Service::TenantDiskService.new(root: Rails.root.join("tmp", "storage"))
expect(service.tenant_root_for("megawonder")).to eq "#{Rails.root}/tmp/storage/tenants/megawonder"
end
end
end