Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

alanpeabody commented Dec 16, 2015

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