Hi
I came across the need for implementing the proxy pattern in Elixir. In particular, I have the concept of content source in my codebase, which represents a place where content can be obtained from and that’s represented by a behaviour ContentSource
, and multiple modules that adhere to the behaviour and that represent multiple content sources: GitHubContentSource
, ShopifyContentSource
…
I’d like to have a module that acts as a proxy and is able to proxy the calls to the right module at runtime based on an identifier (represented by an atom) that represents the content source. For example:
defmodule ContentSource do
@callback get_content(id :: String.t() :: { :ok, String.t() } | { :error, any() }
end
defmodule ContentSources do
def get_content(content_source, id) do
case content_source do
:github -> GitHubContentSource.get_content(id)
# ...
end
end
end
My question is, is there an eloquent way in Elixir to achieve the above without having to manually every single function of the behaviour with a case
in it? I thought about writing a macro that does that automatically given a behaviour and a list of content sources (a pair atom & module name), but I wanted to check if there’s a different Elixir feature at our disposal that I should be using instead.
Thanks in advance,
Pedro