Glenn Jones

Hello πŸ‘‹ Welcome to my corner of the internet. I write here about the different challenges I encounter, and the projects I work on. Find out more about me.

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!”.

Links

Previous: Per-controller resource authorization in elixir phoenix
Next: Elixir ecto - how to group and count records by week