Using Multiverses with Phoenix Presence

Since Phoenix Presence is a behaviour module that autogenerates functions for you with its using directive, it is inappropriate to use Multiverses to override Phoenix Presence. Instead, you will have to override the autogenerated module instead. Presuming that you have created a Presence module like so:

defmodule MyApp.Presence do
  use Phoenix.Presence, otp_app: <my_otp_app>,
                        pubsub_server: <my_pubsub_server>
end

The next step is to place the following module in your tree. You may consider placing it next to your MyApp.Presence module

defmodule Multiverses.MyApp.Presence do
  use Multiverses.Clone,
    module: MyApp.Presence,
    except: [
      fetch: 2, get_by_key: 2, list: 1,
      track: 4, untrack: 3, update: 4
    ]

  def fetch(topic, presences) do
    if is_binary(topic) do
      MyApp.Presence.fetch(Multiverses.Phoenix.PubSub.universal(topic), presences)
    else
      # channel
      MyApp.Presence.fetch(topic, presences)
    end
  end

  def get_by_key(topic, presences) do
    if is_binary(topic) do
      MyApp.Presence.get_by_key(Multiverses.Phoenix.PubSub.universal(topic), presences)
    else
      # channel
      MyApp.Presence.get_by_key(topic, presences)
    end
  end

  def list(topic) do
    if is_binary(topic) do
      MyApp.Presence.list(Multiverses.Phoenix.PubSub.universal(topic))
    else
      # channel
      MyApp.Presence.list(topic)
    end
  end

  def track(pid, topic, key, meta) do
    MyApp.Presence.track(pid, Multiverses.Phoenix.PubSub.universal(topic), key, meta)
  end

  def untrack(pid, topic, key) do
    MyApp.Presence.untrack(pid, Multiverses.Phoenix.PubSub.universal(topic), key)
  end

  def update(pid, topic, key, meta) do
    MyApp.Presence.update(pid, Multiverses.Phoenix.PubSub.universal(topic), key, meta)
  end
end

Now you are ready to use your Presence module in multiverse module! Any module which might need to access it in multiverse mode, should use it as follows:

use Multiverses, with: MyApp.Presence

Important Note:

The Presence struct will have a :topic key whose value includes the universe postfix. If you're matching against this key, be sure to change your match to be "topic" <> _ instead of "topic"