【问题标题】:Elixir/Phoenix 'Magic' Paths长生不老药/凤凰“魔法”路径
【发布时间】:2018-09-09 00:46:12
【问题描述】:

我最近开始使用 Elixir/Phonix (喜欢它),我想了解“魔术”路径 (我指的是它们)是如何工作的以及为 Phoenix 自动配置哪些路径以及它们指向的位置。

通过“魔术”路径,我指的是这样的代码: to: activity_path(@conn, :index) 或 to: user_path(@conn, :update) 或 static_path(@conn, "/js/bootstrap.min.js")。

看来我可以为我创建的任何控制器模块使用“魔术”路径,即

defModule MyWeb.HoobitzController do
  ...
end

所以我可以使用 hoobitz_path() 调用 HoobitzController 中的函数。

这仅适用于控制器吗?是控制器名还是控制器的文件名?

static_path() 显然指向 web 根目录的 /priv 目录,我认为是 Phoenix 核心以某种神秘的方式建立了这个引用。是否有任何其他“魔术”路径指向 Web 根目录中的其他位置?如果有,它们是什么,它们指向哪里?

最后,这些“魔法”路径是否有“真实”名称?社区使用什么术语来指代他们?

【问题讨论】:

    标签: phoenix-framework elixir


    【解决方案1】:

    对于static_path(),您自己已经正确回答了您的问题。

    对于您所谓的 magic 路径,它们来自您的 lib/yourapp_web/router.ex 文件,并且可能与命令行中的 mix phx.routes 任务一起列出。我相信它们被称为“路线路径”。

    您可以在Phoenix code 中查看它是如何构建的。

    【讨论】:

      【解决方案2】:

      static_path 和 Plug.Static

      static_path/1 是 Phoenix.Endpoint 行为中定义的回调函数。查看YOUAPP.Endpoint 模块内部,模块顶部有“use Phoenix.Endpoint, otp_app: :your_app_web”。当你查看source code for static_path/1 时,它实际上返回“/”作为脚本路径的默认值. 基本上,Phoenix 只会为您生成路径,它不知道您的网络应用程序 /priv 目录的位置。

      在您的 Endpoint 模块中,应该有一段代码如下: plug Plug.Static, at: "/", from: :tokenix_admin_web, gzip: false, only: ~w(css fonts images js favicon.ico robots.txt)

      关键字from 是 the file system path to read static assets from. It can be either: a string containing a file system path, an atom representing the application name (where assets will be served from `priv/static`), or a tuple containing the application name and the directory to serve assets from (besides `priv/static`). 当有对“/”路径的请求时,Plug.Static 模块是提供 priv/static 内容的模块。

      Phoenix.Router.Helpers

      魔法路径或生成路径来自 Phoenix.Router.Helpers 模块。 Phoenix.Router 编译前会define helpers function first。它读取您的路由定义可以将其传递给Phoenix.Router.Helpers.define/2,它将根据控制器名称生成。 Helpers are automatically generated based on the controller name. For example, the route: get "/pages/:page", PageController, :show will generate the following named helper: MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello") "/pages/hello" MyAppWeb.Router.Helpers.page_path(conn_or_endpoint, :show, "hello", some: "query") "/pages/hello?some=query" MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello") "http://example.com/pages/hello" MyAppWeb.Router.Helpers.page_url(conn_or_endpoint, :show, "hello", some: "query") "http://example.com/pages/hello?some=query" 它使用元编程来generate helper_path code。 所以真正的名字是helper path。

      您应该查看您的 YourApp、YourApp.Application"、YourApp.Endpoint 和 YourApp.Router 模块。Phoenix 通常会明确定义配置。

      【讨论】:

        猜你喜欢
        • 2021-01-29
        • 2016-02-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-12
        • 1970-01-01
        • 2020-08-31
        • 1970-01-01
        相关资源
        最近更新 更多