Hey guys,
I’m building a cli that communicates with a database. I have this problem that in a few different places I have some logic related to the database’s version that I retrieve by querying the db.
def something() do
if db_version > 2 do
else
end
end
So I don’t want to query the db whenever I need db_version
. One solution would be to pass db_version
via args but imo it’s not the perfect solution as I’d need to pass it to almost every function
Then I thought about using Agent
:
https://hexdocs.pm/elixir/1.14/Agent.html
Often in Elixir there is a need to share or store state that must be accessed from different processes or by the same process at different points in time.
Then I could do something like this:
def something() do
if DBStats.version() > 2 do
else
end
end
defmodule DBStats do
use Agent
def version do
# get version from the agent or query db and update the agent's state
end
end
Is it a good solution? Maybe there is a different (and/or better) way to achieve this?