How do I access an out-of-scope variable from a callback in Elixir

Viewed 348

I have the following (contrived) code:

dbconn # this var holds the database connection
get_from_cache("missing_key")

defp get_from_cache(key) do
  Cachex.get(:my_cache, key, fallback: &from_db/1)
end

defp from_db(key) do
  select_from_db(dbconn)
end

The CacheX package says I can add a fallback function, which will be called if the key is not found in the cache. But that function needs more than just the key. I know I must be missing something here, but how do I access the dbconn variable from the callback in Elixir?

1 Answers

Instead of a reference to a named function, you can pass an anonymous function to Cachex.get which can access variables declared outside the function:

# dbconn holds the database connection
Cachex.get(:my_cache, "missing_key", fallback: fn _key ->
  select_from_db(dbconn)
end)
Related