Reputation: 842
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?
Upvotes: 8
Views: 1661
Reputation: 1
The work of the init function is mainly to make options be available at compile time.This options is then passed to call function as the second argument.
To my opinion i think you can decide to have options or not depending on the task the plug function or module is meant to accomplish .
Upvotes: 0
Reputation: 166
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.
Upvotes: 12