How to simplify these code? (like defdelegate but with a constant parameter)

  def get(cache_key) do
    :app_cache |> Cachex.get(cache_key)
  end

  def get!(cache_key) do
    :app_cache |> Cachex.get!(cache_key)
  end

  def put(cache_key, cache_value) do
    :app_cache |> Cachex.put(cache_key, cache_value)
  end

  def put!(cache_key, cache_value) do
    :app_cache |> Cachex.put!(cache_key, cache_value)
  end

  def keys do
    :app_cache |> Cachex.keys()
  end

  def purge do
    :app_cache |> Cachex.purge()
  end

  ## ....

Thanks!

I wouldn’t, the code there is simple and easy to understand :slight_smile:

6 Likes

(Unofficial) Style Guide: Avoid Needless Pipelines

def get(cache_key),
  do: Cachex.get(:app_cache, cache_key)

def get!(cache_key),
  do: Cachex.get!(:app_cache, cache_key)

  # etc
7 Likes

The only thing I’d probably change (besides removing the pipelines as @peerreynders already suggested) is to move the constant :app_cache into a module attribute, so that you write the actual value only once (and use a symbolic reference everywhere else). This means that if you’d ever want to change the name of the cache, you only need to do so in one place.

3 Likes

I think that the actual question was “how to make a proxy for same-named functions with injecting one constant argument”:

defmodule Proxy do
  @cache_name :app_cache
  @proxy_to Cachex

  [
    get: 1,
    get!: 1,
    put: 2,
    put!: 2,
    keys: 0,
    purge: 0,
  ]
  |> Enum.map(fn {name, arity} ->
    args =
      if arity > 0 do
        Macro.generate_arguments(arity, __MODULE__)
      else
        []
      end
    def unquote(name)(unquote_splicing(args)) do
      unquote(@proxy_to).unquote(name)(unquote(@cache_name), unquote_splicing(args))
    end
  end)
end

But I agree with previous comments - if you have to do it with just one module and few functions like in example above - the better and clearer way is to keep it as is.

4 Likes

The code is rather clean. The only thing I would do would be to following the community style guidelines:

  def get(cache_key), do: Cachex.get(:app_cache, cache_key)

  def get!(cache_key), do: Cachex.get!(:app_cache, cache_key)
 
  def put(cache_key, cache_value), do:
    Cachex.put(app_cache, cache_key, cache_value)
1 Like