Packages
unleash_fresha
2.0.0-git-4b61
5.1.4
5.1.3
5.1.2
5.1.1
5.1.0
5.0.0
4.0.0
4.0.0-git-bda3
3.0.1
3.0.0
2.1.0
2.0.1
2.0.0-git-75d8
2.0.0-git-67b2
2.0.0-git-4b61
2.0.0-git-49f4
1.16.0
1.15.0
1.14.1-git-e754
1.14.0
1.14.0-git-71e9
1.13.0
1.13.0-git-4ba6
1.12.0
1.11.0
1.11.0-git-1b62
1.10.2
1.10.2-git-b835
1.10.1
1.10.0
1.9.3-alpha0
1.9.2
1.9.1
1.9.0
An Unleash Feature Flag client for Elixir, forked from [unleash](https://gitlab.com/afontaine/unleash_ex)
Current section
Files
Jump to
Current section
Files
lib/unleash/cache.ex
defmodule Unleash.Cache do
@moduledoc """
This module is a cache backed by an ETS table. We use it to allow for multiple
threads to read the feature flag values concurrently on top of minimizing
network calls
"""
@cache_table_name :unleash_cache
def cache_table_name, do: @cache_table_name
@doc """
Will create a new ETS table named `:unleash_cache`
"""
def init(existing_features \\ [], table_name \\ @cache_table_name) do
:ets.new(table_name, [:named_table, read_concurrency: true])
upsert_features(existing_features, table_name)
end
@doc """
Will return all values currently stored in the cache
"""
def get_all_feature_names(table_name \\ @cache_table_name) do
features = :ets.tab2list(table_name)
Enum.map(features, fn {name, _feature} ->
name
end)
end
@doc """
Will return all features stored in the cache
"""
def get_features(table_name \\ @cache_table_name) do
features = :ets.tab2list(table_name)
Enum.map(features, fn {_name, feature} ->
feature
end)
end
@doc """
Will return the feature for the given name stored in the cache
"""
def get_feature(name, table_name \\ @cache_table_name)
def get_feature(name, table_name) when is_binary(name) do
case :ets.lookup(table_name, name) do
[{^name, feature}] -> feature
[] -> nil
end
end
def get_feature(name, table_name) when is_atom(name), do: get_feature(Atom.to_string(name), table_name)
@doc """
Will upsert (create or update) the given features in the cache
This will clear the existing peristed features to prevent stale reads
"""
def upsert_features(features, table_name \\ @cache_table_name) do
:ets.delete_all_objects(table_name)
Enum.each(features, fn feature ->
upsert_feature(feature.name, feature, table_name)
end)
end
defp upsert_feature(name, value, table_name) when is_binary(name) do
:ets.insert(table_name, {name, value})
end
defp upsert_feature(name, value, table_name) when is_atom(name) do
upsert_feature(Atom.to_string(name), value, table_name)
end
end