Skip to content

Instantly share code, notes, and snippets.

@Kalimaha
Last active February 5, 2019 02:07
Show Gist options
  • Select an option

  • Save Kalimaha/d42ffe235fb488e891e37d88f5ca07a8 to your computer and use it in GitHub Desktop.

Select an option

Save Kalimaha/d42ffe235fb488e891e37d88f5ca07a8 to your computer and use it in GitHub Desktop.
Elixir ETS
defmodule SwitchWeb.ETSServiceTest do
use ExUnit.Case
@cache_name :switches_cache
@value_1 "eggs"
@value_2 "bacon"
test "initialize cache" do
initialize()
assert lookup(:this_is_the_key) == {:ok, nil}
end
test "value lookup" do
initialize()
insert(:this_is_the_key, %{spam: @value_1})
insert(:this_is_the_key, %{spam: @value_2})
{:ok, value} = lookup(:this_is_the_key)
assert value[:spam] == @value_2
end
test "access a key from a non-existent cache" do
try do
insert(:this_is_the_key, %{spam: @value_1})
rescue
e in ArgumentError -> assert e == %ArgumentError{message: "argument error"}
end
end
test "deletes a key from the cache" do
initialize()
insert(:this_is_the_key, %{spam: @value_1})
delete(:this_is_the_key)
assert lookup(:this_is_the_key) == {:ok, nil}
end
defp initialize do
:ets.new(@cache_name, [:set, :protected, :named_table])
end
defp insert(key, value) do
:ets.insert(@cache_name, {key, value})
end
defp lookup(key) do
cache_value = :ets.lookup(@cache_name, key)
case cache_value do
[] -> {:ok, nil}
_ -> {:ok, cache_value[key]}
end
end
defp delete(key) do
:ets.delete(@cache_name, key)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment