Reputation: 55
I want to route incoming requests randomly.
So far I've only come up with this:
defmodule Test.PageController do
use Test.Web, :controller
plug :assign_random_number
def index(%{assigns: %{random_number: random_number}} = conn, _params)
when random_number > 0.1 do
render conn, "index.html", fortune: "one"
end
def index(conn, _params) do
render conn, "index.html", fortune: "two"
end
defp assign_random_number(conn, _params) do
:random.seed(:erlang.now)
assign(conn, :random_number, :random.uniform)
end
end
Is it possible to have this "randomization" logic in router.ex
? Like in Sinatra
get "/", :random_number > 0.1 do
"one"
end
get "/" do
"two"
end
Upvotes: 2
Views: 125
Reputation: 33537
You can't (and shouldn't) do that in Elixir at the routing level. In fact, you can't even do that in Sinatra! The code you posted is invalid Ruby:
get "/", :random_number > 0.1 do
"one"
end
# => ArgumentError: comparison of Symbol with 0.1 failed
Here's how'd you'd actually accomplish this in Sinatra:
get "/" do # <- Routing layer
rand > 0.1 ? 'one' : 'two' # <- Response/controller layer
end
Note that we're depending on our response/controller layer to handle the randomization. We can do something similar in Elixir:
defmodule Test.PageController do
use Test.Web, :controller
def index(conn, _params) do
render conn, "index.html", fortune: make_fortune
end
defp make_fortune do
if :random.uniform > 0.1, do: "one", else: "two"
end
end
Upvotes: 1