Optional routing parameters in Phoenix Framework
<p>I've started to teach myself <a href="http://www.phoenixframework.org/" rel="noreferrer">Phoenix Framework</a> and their documentation is pretty good. I have however hit a stumbling block when it comes to specifying optional routing parameters. The <a href="http://www.phoenixframework.org/docs/routing" rel="noreferrer">Phoenix Framework Routing Documentation</a> makes no mention of this as a feature, so I'm assuming the onus falls on the dev to come up with a solution.</p>

<p>I'll lay out my use case:</p>

<ol>
<li>User visits site at <code>/page/test</code>, a custom <a href="http://www.phoenixframework.org/docs/understanding-plug" rel="noreferrer">Plug</a> then implements some code to find or assign a <code>locale</code> to the connection.</li>
<li>Since there's no <code>:locale</code> parameter in the path, the default is used as per the line in my <strong>pipeline</strong>, which is <code>plug HelloPhoenix.Plugs.Locale, "en"</code>.</li>
<li>User visits site at <code>/fr/page/test</code>, and the same code gets executed in the pipeline, except time as the <code>:locale</code> parameter is present in the route, the custom Plug (<code>HelloPhoenix.Plugs.Locale</code>).</li>
</ol>

<p>Now from a routing perspective, if I can't specify that the <code>:locale</code> parameter is optional, I end up with double the number of routes, e.g.:</p>

<pre><code>scope "/", HelloPhoenix do
  use_pipeline :browser
  plug HelloPhoenix.Plugs.Locale, "en"

  # Route without locale
  get "/page/:slug", PageController, :show
  # Route with locale
  get "/:locale/page/:slug", PageController, :show
end
</code></pre>

<p>as you can tell, this could quickly become very arduous and repetitive without the ability to specify an optional routing parameter.</p>

<p>No I <em>do have a workaround</em>, which I'll post in an answer, but I'm not sure if it's (a) right, and (b) the easiest solution, since I'm new to Erlang, Elixir and Phoenix (I'm coming from a background in Ruby &amp; PHP OOP).</p>