diff --git a/lib/phoenix/verified_routes.ex b/lib/phoenix/verified_routes.ex index 0585bde717..6c5b09c619 100644 --- a/lib/phoenix/verified_routes.ex +++ b/lib/phoenix/verified_routes.ex @@ -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 @@ -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. @@ -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 diff --git a/test/phoenix/verified_routes_test.exs b/test/phoenix/verified_routes_test.exs index 3fcb9654d6..9ffc58b44e 100644 --- a/test/phoenix/verified_routes_test.exs +++ b/test/phoenix/verified_routes_test.exs @@ -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"