Skip to content

Instantly share code, notes, and snippets.

@Enforcer
Created March 23, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Enforcer/39f853490148a0ba42ca77bbcd758053 to your computer and use it in GitHub Desktop.
Save Enforcer/39f853490148a0ba42ca77bbcd758053 to your computer and use it in GitHub Desktop.
defmodule Router do
def get do
end
def owner_id_currency_to_name(owner_id, currency_id) do
try do
String.to_existing_atom("wallet-#{owner_id}-#{currency_id}")
rescue
ArgumentError -> String.to_atom("wallet-#{owner_id}-#{currency_id}")
end
end
end
defmodule Wallet do
use GenServer
def start_link(name) do
GenServer.start_link(__MODULE__, 0, name: name)
end
def balance(name) do
GenServer.call(name, :balance)
end
def credit(name, value) do
GenServer.call(name, {:credit, value})
end
def handle_call(:balance, _from, state) do
{:reply, state, state}
end
def handle_call({:credit, value}, _from, state) do
new_state = state + value
{:reply, new_state, new_state}
end
end
defmodule MySupervisor do
use DynamicSupervisor
def start_link(arg) do
DynamicSupervisor.start_link(__MODULE__, arg, name: __MODULE__)
end
def init(_arg), do: DynamicSupervisor.init(strategy: :one_for_one)
def ensure_running(name) do
spec = {Wallet, name}
DynamicSupervisor.start_child(__MODULE__, spec)
end
end
MySupervisor.start_link([])
# in router
owner_id_1 = 1
currency_id_1 = 2
name_1 = Router.owner_id_currency_to_name(owner_id_1, currency_id_1)
MySupervisor.ensure_running(name_1)
IO.inspect(Wallet.balance(name_1))
IO.inspect(Wallet.credit(name_1, 10))
IO.inspect(Wallet.balance(name_1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment