Glenn Jones's Blog

Default arguments in an elixir plug

The init and call construction of plugs give you the ability to provide default arguments. Read more about it here. This is a short explenation of how you can work with that.

defmodule Project.CakeDescriber
  def init(opts) do
    default_opts = %{color: red}
    Map.merge(default_opts, opts)
  end

  def call(conn, opts \\ %{}) do
    color = Map.fetch!(opts, :color)
    taste = Map.fetch!(opts, :taste)
    IO.puts(#{color} and #{taste} cakes are the best!”)
  end

end

Now if you call:

Project.CakeDescriber, %{taste: fruity}

It will return: “red and fruity cakes are the best!”.

Then, if you call:

Project.CakeDescriber, %{taste: carrot-y, color: purple}

It will return: “purple and carrot-y cakes are the best!”.

comments powered by Disqus