在我的凤凰应用程序中,我有一个数据格式化功能,我希望所有控制器都可以访问它 -
def prettify({message, values}) do
Enum.reduce values, message, fn {k, v}, acc ->
String.replace(acc, "%{#{k}}", to_string(v))
end
end
Phoenix应用程序的文件结构中应该包含全局可访问的函数,以及如何调用它们?
答案 0 :(得分:1)
我通常会为音乐会的特定区域创建一个助手模块。例如,我可能有web/views/ViewHelpers.ex
或web/controllers/ControllerHelpers.ex
文件。然后我将它们包含在web/web.ex
文件中的相应位置。
以下是我写的聊天应用的web.ex文件的一部分。
defmodule UcxChat.Web do
def service do
quote do
import Ecto.Query
alias UcxChat.{Repo, RoomChannel, UserChannel, Settings}
alias UcxChat.ServiceHelpers, as: Helpers
require UcxChat.SharedView
use UcxChat.Gettext
import Phoenix.HTML, only: [safe_to_string: 1]
end
end
def controller do
quote do
use Phoenix.Controller
use UcxChat.Utils
alias UcxChat.Repo
import Ecto
import Ecto.Query
import UcxChat.Router.Helpers
use UcxChat.Gettext
alias UcxChat.Settings
end
end
def view do
quote do
use Phoenix.View, root: "web/templates"
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
use UcxChat.Utils
alias UcxChat.Settings
import Phoenix.HTML.Tag
import UcxChat.Router.Helpers
import UcxChat.ErrorHelpers
use UcxChat.Gettext
import UcxChat.SharedView
require UcxChat.SharedView
alias UcxChat.Permission
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
我有一些带有宏的辅助模块,所以你会看到一些use ...
例子。