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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With