Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Plug.Router what is the point of the init function?

Tags:

elixir

Trying to get an understanding on Plug, specifically Plug.Router. From the documentation (http://hexdocs.pm/plug/Plug.Router.html). From the specification plugs have an init function that is called at initalization time to pass in options, but those don't seem to be available in the defined routes.

What is the reason for not having options available and is there a pattern that would allow it to be?

like image 211
Peck Avatar asked Jan 28 '16 05:01

Peck


1 Answers

Heres an excerpt from the book - Programming Phoenix:

"Sometimes, you might need Phoenix to do some heavy lifting to transform options. That’s the job of the init function. init happens at compile time. Plug will use the result of init as the second argument to call. Because init is often called at compilation time, it is the perfect place to validate options and prepare some of the work. That way, call can be as fast as possible. Since call is the workhorse, we want it to do as little work as possible. "

For example - Using a plug in your routes.ex file

  pipeline :api do
    plug :accepts, ["json"]
    plug Example.Authenticated, repo: Example.Repo
  end

repo: Example.Repo is the options being passed - to the init function inside Example.Repo

defmodule Example.Authenticated do
  import Plug.Conn

  def init(opts) do 
   Keyword.fetch!(opts, :repo)
  end

  def call(conn, repo) do
   ...
  end

end

I'm assuming in the case of Plug.Router - at compile time modifications could be - loading modules that build/modify routes - possibly from an external source? Depends on what your trying to accomplish.

like image 153
orion_e Avatar answered Nov 17 '22 07:11

orion_e