Nebulex.Adapters.Nil (Nebulex v3.0.0-rc.1)

View Source

The Nil adapter is a special cache adapter that turns off the cache. It loses all the items saved on it and returns nil for all read operations and true for all save operations. This adapter is mostly useful for tests.

Shared options

All of the cache functions accept the following options when using this adapter:

  • :before (function of arity 0) - Pre-hook function. It calls the given function before the cache command is executed.

  • :after_return (function of arity 1) - Post-hook function. It calls the given function after the cache command is executed, and the returned result is passed as an argument.

Example

Suppose you have an application using Ecto for database access and Nebulex for caching. Then, you have defined a cache and a repo within it. Since you are using a database, there might be some cases where you may want to turn off the cache to avoid issues when running the test. For example, in some test cases, when accessing the database, you expect no data, but you can still get unexpected data since the cache is not flushed. Therefore, you must delete all entries from the cache before running each test to ensure the cache is always empty. Here is where the Nil adapter comes in, instead of adding code to flush the cache before each test, you could define a test cache using the Nil adapter for the tests.

On one hand, you have defined the cache in your application within lib/my_app/cache.ex:

defmodule MyApp.Cache do
  use Nebulex.Cache,
    otp_app: :my_app,
    adapter: Nebulex.Adapters.Local
end

On the other hand, in the tests, you have defined the test cache within test/support/test_cache.ex:

defmodule MyApp.TestCache do
  use Nebulex.Cache,
    otp_app: :my_app,
    adapter: Nebulex.Adapters.Nil
end

You must tell the app what cache to use depending on the environment. For tests, you configure MyApp.TestCache; otherwise, it is always MyApp.Cache. You can do this by introducing a new config parameter to decide which cache module to use. For tests, you can define the config config/test.exs:

config :my_app,
  nebulex_cache: MyApp.TestCache,
  ...

The final piece is to read the config parameter and start the cache properly. Within lib/my_app/application.ex, you could have:

def start(_type, _args) do
  children = [
    {Application.get_env(:my_app, :nebulex_cache, MyApp.Cache), []},
  ]

  ...

As you may notice, MyApp.Cache is used by default unless the :nebulex_cache option points to a different module, which will be when tests are executed (test env).