ericgray

ericgray

How does Phoenix pattern matching work on Dynamic Routes

I never fully understood how Phoenix is able to route urls with params like "users/1" to the correct Controller, Action. From what I understand Phoenix pattern matches the path on incoming requests. For example, its easy to see how "/users" will match this get macro.

get "/users", UserController, :index

But how does Phoenix route "/users/1" to this.

get "/users/:id", UserController, :show  

How does Phoenix match "/users/1" to "/users/:id"
I know it can’t be traditional pattern matching otherwise you’d get a no function clause matching error.

There must be some kind of macro magic happening behind the scenes that I don’t understand.

Marked As Solved

chrismccord

chrismccord

Creator of Phoenix

simplified, we generate function heads like this:

def match(conn, "GET", ["users"]), do: UserController.call(conn, UserController.init(:index))
def match(conn, "GET", ["users", id]) do
  new_params = Map.merge(conn.params, %{"id" => id})
  UserController.call(%{conn | params: new_params}, UserController.init(:show))
end
def match(conn, _, _) do: # raise Phoenix.NotFoundError ...
16
Post #4

Also Liked

blatyo

blatyo

Conduit Core Team

It delegates part of that responsibility to plug and this function:

https://github.com/elixir-plug/plug/blob/master/lib/plug/router/utils.ex#L52-L67

The primary logic starts here:

https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/router.ex#L321-L324

The thing that generates the final AST is here:

https://github.com/phoenixframework/phoenix/blob/master/lib/phoenix/router.ex#L353-L386

My understanding is that it effectively turns into something like:

def __match_route__(conn, :get, ["users", id], "www.google.com")

That means, when it initially gets a request, it just splits the path by / and can then match on that.

ericgray

ericgray

Hey Chris thanks, that really pointed me in the right direction. I dug a little deeper and found this video Erlang Factory 2014 – Write Less, Do More (and Have Fun!) with Elixir Macros The video is a gem and really helped me understand Macros.

I was always curios how the Router layer worked in Phoenix. For any one interested about 31:22 Chris explains how routes work. I also purchased Metaprogramming Elixir, used my Elixir Forum discount and got it for 7 bucks. What a steal!

Where Next?

Popular in Questions Top

skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lists...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Other popular topics Top

New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement