Nebulex.Adapters.Nil (Nebulex v3.1.0)

Copy Markdown View Source

The Nil adapter is a special cache adapter that turns off the cache. It drops everything written to it, behaves as if every key were missing on reads, and reports success on all writes. It 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 that uses Ecto for database access and Nebulex for caching, so it defines a repo and a cache. In some tests you may want to turn the cache off. For example, a test that expects no data from the database can still get data from the cache if the cache was not flushed, so you would have to delete all entries before each test. Instead of adding code to flush the cache before each test, you can define a test cache that uses the Nil adapter.

The application cache is defined in lib/my_app/cache.ex:

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

The test cache is defined in test/support/test_cache.ex:

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

Then tell the app which cache to use per environment: MyApp.TestCache in tests and MyApp.Cache otherwise. One way is a config parameter that picks the cache module. In config/test.exs:

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

The last piece is to read the config parameter and start that cache. In lib/my_app/application.ex:

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

  ...

MyApp.Cache is used by default unless the :nebulex_cache option points to a different module, which is the case in the test environment.