Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
defmodule Features do
use GenServer
@features [chat: true]
def enable(feature), do: GenServer.call(__MODULE__, {:toggle, feature, true})
def disable(feature), do: GenServer.call(__MODULE__, {:toggle, feature, false})
def enabled?(feature) do
case :ets.lookup(__MODULE__, feature) do
[] -> Keyword.get(@features, feature, false)
[{_, enabled}] -> enabled
end
catch
:error, :badarg ->
# Table is missing
Keyword.get(@features, feature, false)
end
def start_link(_), do: GenServer.start_link(__MODULE__, [], name: __MODULE__)
def init(_) do
:ets.new(__MODULE__, [:set, :public, :named_table, read_concurrency: true)
for {feature, enabled} <- @features, do: :ets.insert(__MODULE__, {feature, enabled})
{:ok, nil}
end
def handle_call({:toggle, feature, enabled}, _from, state) do
:ets.update_element(__MODULE__, feature, {2, enabled})
{:reply, :ok, state}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment