Skip to content
Closed
24 changes: 23 additions & 1 deletion lib/phoenix/verified_routes.ex
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,7 @@ defmodule Phoenix.VerifiedRoutes do
defp to_param(data), do: Phoenix.Param.to_param(data)

defp build_route(route_ast, sigil_p, env, endpoint_ctx, router) do
config = Module.get_attribute(env.module, :phoenix_verified_config, [])
config = verified_config!(env)

router =
case Macro.expand(router, env) do
Expand Down Expand Up @@ -1026,6 +1026,8 @@ defmodule Phoenix.VerifiedRoutes do
end

defp attr!(env, :endpoint) do
verified_config!(env)

Module.get_attribute(env.module, :endpoint) ||
raise """
expected @endpoint to be set. For dynamic endpoint resolution, use path/2 instead.
Expand All @@ -1037,9 +1039,29 @@ defmodule Phoenix.VerifiedRoutes do
end

defp attr!(env, name) do
verified_config!(env)

Module.get_attribute(env.module, name) || raise "expected @#{name} module attribute to be set"
end

defp verified_config!(env) do
case Module.get_attribute(env.module, :phoenix_verified_config) do
nil ->
raise ArgumentError, """
attempted to use Phoenix.VerifiedRoutes without calling `use Phoenix.VerifiedRoutes` first.

You must use `use Phoenix.VerifiedRoutes` with the appropriate options instead of importing it:

use Phoenix.VerifiedRoutes, endpoint: MyAppWeb.Endpoint, router: MyAppWeb.Router

See the documentation for more details on configuration options.
"""

config ->
config
end
end

defp static_path?(path, statics) do
Enum.find(statics, &String.starts_with?(path, "/" <> &1))
end
Expand Down
11 changes: 11 additions & 0 deletions test/phoenix/verified_routes_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,17 @@ defmodule Phoenix.VerifiedRoutesTest do
:code.delete(__MODULE__.SigilPPrefix)
end

test "~p raises when VerifiedRoutes is imported instead of used" do
assert_raise ArgumentError,
~r|attempted to use Phoenix.VerifiedRoutes without calling|,
fn ->
defmodule BadImportedVerifiedRoutes do
import Phoenix.VerifiedRoutes
def test, do: ~p"/posts/1"
end
end
end

test "path arities" do
assert path(Endpoint, ~p"/posts/1") == "/posts/1"
assert path(conn_with_endpoint(), ~p"/posts/1") == "/posts/1"
Expand Down