Last active
February 5, 2019 02:07
-
-
Save Kalimaha/d42ffe235fb488e891e37d88f5ca07a8 to your computer and use it in GitHub Desktop.
Elixir ETS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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