Created
September 6, 2022 17:30
-
-
Save rugyoga/3fde53ebdf527a937061c1e5b2e93ddf to your computer and use it in GitHub Desktop.
Agent that performs file cacheing
This file contains 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 Audit.FileCache do | |
@moduledoc """ | |
Simple File cache Agent | |
""" | |
use Agent | |
def start_link(_args) do | |
Agent.start_link(fn -> %{} end, name: __MODULE__) | |
end | |
def get(filename) do | |
Agent.get_and_update( | |
__MODULE__, | |
fn state -> | |
if cached = Map.get(state, filename) do | |
{cached, state} | |
else | |
file = File.stream!(filename) | |
{file, Map.put(state, filename, file)} | |
end | |
end | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment