Skip to content

Instantly share code, notes, and snippets.

@alanpeabody
Last active July 16, 2017 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alanpeabody/0802e6051d141e2043c3 to your computer and use it in GitHub Desktop.
Save alanpeabody/0802e6051d141e2043c3 to your computer and use it in GitHub Desktop.
JS's LocalStorage in Elixir - A super simple intro to GenServer for js devs
defmodule LocalStorage do
use GenServer
# API
def start_link do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
end
def set_item(key, val) do
GenServer.cast(__MODULE__, {:set_item, key, val})
end
def get_item(key) do
GenServer.call(__MODULE__, {:get_item, key})
end
def remove_item(key) do
GenServer.cast(__MODULE__, {:remove_item, key})
end
def clear() do
GenServer.cast(__MODULE__, :clear)
end
def all() do
GenServer.call(__MODULE__, :all)
end
# GenServer Callbacks
def handle_cast({:set_item, key, val}, store) do
{:noreply, Map.put(store, key, val)}
end
def handle_cast({:remove_item, key}, store) do
{:noreply, Map.drop(store, key)}
end
def handle_cast(:clear, state) do
{:noreply, %{}}
end
def handle_call({:get_item, key}, _from, store) do
{:reply, Map.get(store, key), store}
end
def handle_call(:all, _from, state) do
{:reply, state, state}
end
end
@alanpeabody
Copy link
Author

Usage:

iex
iex(1)> c "local_storage.ex"
[LocalStorage]
iex(2)> LocalStorage.start_link
{:ok, #PID<0.102.0>}
iex(3)> LocalStorage.all
%{}
iex(4)> LocalStorage.set_item(:foo, "bar")
:ok
iex(5)> LocalStorage.get_item(:foo)
"bar"
iex(6)> LocalStorage.get_item(:nope)
nil
iex(7)> LocalStorage.all
%{foo: "bar"}
iex(8)> LocalStorage.clear
:ok
iex(9)> LocalStorage.all
%{}

@jordpo
Copy link

jordpo commented Dec 17, 2015

what happens when your server crashes? :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment