Default arguments in an elixir plug

by Glenn square thumb Glenn Jones, published on 22/08/16

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

>> Elixir ecto - how to group and count records by week

<< Per-controller resource authorization in elixir phoenix

Back to glennjon.es

comments powered by Disqus