adding :ets to keep track of current value
This commit is contained in:
@ -14,9 +14,10 @@ defmodule Clip.Application do
|
||||
# Start the PubSub system
|
||||
{Phoenix.PubSub, name: Clip.PubSub},
|
||||
# Start the Endpoint (http/https)
|
||||
ClipWeb.Endpoint
|
||||
ClipWeb.Endpoint,
|
||||
# Start a worker by calling: Clip.Worker.start_link(arg)
|
||||
# {Clip.Worker, arg}
|
||||
Clip.Currents
|
||||
]
|
||||
|
||||
# See https://hexdocs.pm/elixir/Supervisor.html
|
||||
|
||||
23
lib/clip/board.ex
Normal file
23
lib/clip/board.ex
Normal file
@ -0,0 +1,23 @@
|
||||
defmodule Clip.Board do
|
||||
|
||||
alias Clip.Currents
|
||||
|
||||
def init(user) do
|
||||
Phoenix.PubSub.subscribe(Clip.PubSub, user.email)
|
||||
Currents.get(user.email)
|
||||
end
|
||||
|
||||
def paste(user, snippet) do
|
||||
Phoenix.PubSub.broadcast(Clip.PubSub, user.email, {:snippet_pasted, %{snippet: snippet}})
|
||||
Currents.set(user.email, snippet)
|
||||
end
|
||||
|
||||
def normalize(pnumber, local_pref \\ "0351", country_pref \\ "0049") do
|
||||
pnumber
|
||||
|> String.replace(~r/^\s*\+/, "00")
|
||||
|> String.replace(~r/\D/, "")
|
||||
|> String.replace(~r/^00+/, "00")
|
||||
|> String.replace(~r/^(?=[1-9])/, local_pref)
|
||||
|> String.replace(~r/^0(?=[1-9])/, country_pref)
|
||||
end
|
||||
end
|
||||
41
lib/clip/currents.ex
Normal file
41
lib/clip/currents.ex
Normal file
@ -0,0 +1,41 @@
|
||||
defmodule Clip.Currents do
|
||||
use GenServer
|
||||
require Logger
|
||||
|
||||
@purge_interval :timer.minutes(60)
|
||||
|
||||
def start_link(_) do
|
||||
GenServer.start_link(__MODULE__, %{}, name: ClipCurrents)
|
||||
end
|
||||
|
||||
def init(opts) do
|
||||
:ets.new(:users_clips, [:set, :named_table, :public])
|
||||
state = %{
|
||||
interval: opts[:purge_interval] || @purge_interval,
|
||||
timer: nil
|
||||
}
|
||||
{:ok, schedule_purge(state)}
|
||||
end
|
||||
|
||||
def set(email_addr, value) do
|
||||
:ets.insert(:users_clips, {email_addr, value})
|
||||
:ok
|
||||
end
|
||||
|
||||
def get(email_addr) do
|
||||
cur_val = case :ets.lookup(:users_clips, email_addr) do
|
||||
[{^email_addr, value}] -> value
|
||||
[] -> ""
|
||||
end
|
||||
{:ok, cur_val}
|
||||
end
|
||||
|
||||
def handle_info(:purge, state) do
|
||||
Logger.info("should purge old entries but doesn't, yet")
|
||||
{:noreply, schedule_purge(state)}
|
||||
end
|
||||
|
||||
defp schedule_purge(state) do
|
||||
%{state | timer: Process.send_after(self(), :purge, state.interval)}
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user