
Read Time:1 Minute, 0 Second
elixir 的模块属性除了可帮助我们建立模块 (module) 的说明, 函数 (function) 的说明外, 也可帮助我们定义常数。
elixir module attributes
elixir 的模块属性, 区分为:
- @moduledoc: 代表著模块 (module) 的说明; 在下面的例子, @moduledoc说明了模块 Servy.Handler 主要负责 “Handles HTTP requests. “。
defmodule Servy.Handler do
@moduledoc "Handles HTTP requests. "
- @doc: 代表著函数 (function) 的说明; 在下面的例子, @doc 说明了函数 handle 主要负责 “Transforms the request into a response.”
@doc "Transforms the request into a response."
def handle(request) do
request
|> parse
|> rewrite_path
|> log
|> route
|> track
|> format_response
end
- @ (定义常数): 我们可使用 @ 在模块内定义常数。在下面的例子中, 我们定义了常数 @page_path 来代表著函数 Path.expand(“../../pages”, __DIR__) 执行后的回传值; 某个的路径。
defmodule Servy.Handler do
@moduledoc "Handles HTTP requests. "
@page_path Path.expand("../../pages", __DIR__)
当我们定义了常数 @page_path 在模块内, 则从 @page_path 在模块内的位置之后的所有函数, 都可以使用 @page_path。在下面的例子中, @page_path 在模块 Servy.Handler 内所有的函数之前, 所以, 模块 Servy.Handler 内的所有函数, 都可以使用 @page_path。
defmodule Servy.Handler do
@moduledoc "Handles HTTP requests. "
@page_path Path.expand("../../pages", __DIR__)
@doc "Transforms the request into a response."
def handle(request) do
request
|> parse
|> rewrite_path
|> log
|> route
|> track
|> format_response
end
def parse(request) do
def route(%{method: "GET", path: "/about"} = conv) do
@page_path
|> Path.join("about.html")
|> File.read
|> handle_file(conv)
end