From 8c91ec6d6562496bf892c045cc8bcb0e9f90b0b0 Mon Sep 17 00:00:00 2001 From: Jeff Deville Date: Thu, 8 Sep 2016 17:34:58 -0400 Subject: [PATCH] Also provide the ability to extract the tenant id from the prefix --- lib/apartmentex/prefix_builder.ex | 4 ++++ test/apartmentex_test.exs | 9 +++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/apartmentex/prefix_builder.ex b/lib/apartmentex/prefix_builder.ex index 018a034..d00a810 100644 --- a/lib/apartmentex/prefix_builder.ex +++ b/lib/apartmentex/prefix_builder.ex @@ -12,4 +12,8 @@ defmodule Apartmentex.PrefixBuilder do def build_prefix(tenant) do @schema_prefix <> Integer.to_string(tenant.id) end + + def extract_tenant(table_prefix) do + String.replace_prefix(table_prefix, @schema_prefix, "") + end end diff --git a/test/apartmentex_test.exs b/test/apartmentex_test.exs index 88b0a9c..db15022 100644 --- a/test/apartmentex_test.exs +++ b/test/apartmentex_test.exs @@ -165,7 +165,7 @@ defmodule Apartmentex.ApartmentexTest do prefix = %Note{} |> set_tenant(@tenant_id) |> Ecto.get_meta(:prefix) - assert prefix == "tenant_2" + assert prefix == "tenant_#{@tenant_id}" end test ".set_tenant/2 changeset adds the tenant prefix" do @@ -174,7 +174,7 @@ defmodule Apartmentex.ApartmentexTest do |> Map.fetch!(:data) |> Ecto.get_meta(:prefix) - assert prefix == "tenant_2" + assert prefix == "tenant_#{@tenant_id}" end test ".set_tenant/2 queryable adds the tenant prefix" do @@ -184,4 +184,9 @@ defmodule Apartmentex.ApartmentexTest do assert prefix == "tenant_#{@tenant_id}" end + + test ".extract_tenant/1 removes the prefix from the schema" do + assert Apartmentex.PrefixBuilder.extract_tenant("tenant_#{@tenant_id}") == "#{@tenant_id}" + assert Apartmentex.PrefixBuilder.extract_tenant("tenant_somestring") == "somestring" + end end