簡(jiǎn)介
通過增加自定義 Mix 任務(wù)來擴(kuò)展你的 Elixir 項(xiàng)目是很常見需求进萄。在我們學(xué)習(xí)如何給我們的項(xiàng)目創(chuàng)建特定 Mix 任務(wù)之前,讓我們看一個(gè)已經(jīng)存在的任務(wù)锐峭。
$ mix phoenix.new my_phoenix_app
* creating my_phoenix_app/config/config.exs
* creating my_phoenix_app/config/dev.exs
* creating my_phoenix_app/config/prod.exs
* creating my_phoenix_app/config/prod.secret.exs
* creating my_phoenix_app/config/test.exs
* creating my_phoenix_app/lib/my_phoenix_app.ex
* creating my_phoenix_app/lib/my_phoenix_app/endpoint.ex
* creating my_phoenix_app/test/views/error_view_test.exs
...
正如上面我們看到的 shell 命令中鼠,Phoenix 有一個(gè)自定義的 Mix 任務(wù)去生成一個(gè)新項(xiàng)目。用 Elixir 創(chuàng)建類似的東西很容易沿癞。
起步
首先創(chuàng)建一個(gè)基本的 Mix 項(xiàng)目援雇。
$ mix new hello
* creating README.md
* creating .gitignore
* creating mix.exs
* creating config
* creating config/config.exs
* creating lib
* creating lib/hello.ex
* creating test
* creating test/test_helper.exs
* creating test/hello_test.exs
Your Mix project was created successfully.
You can use "mix" to compile it, test it, and more:
cd hello
mix test
Run "mix help" for more commands.
在 Mix 為我們生成的 lib/hello.ex 文件中,創(chuàng)建一個(gè)會(huì)輸出 “Hello, World!” 的函數(shù)椎扬。
defmodule Hello do
@doc """
每次調(diào)用都會(huì)輸出 `Hello, World!`
"""
def say do
IO.puts("Hello, World!")
end
end
自定義 Mix 任務(wù)
來創(chuàng)建我們的自定義 Mix 任務(wù)吧惫搏,新建一個(gè)目錄以及文件 hello/lib/mix/tasks/hello.ex。
defmodule Mix.Tasks.Hello do
use Mix.Task
@shortdoc "Simply runs the Hello.say/0 command."
def run(_) do
# 調(diào)用我們剛才創(chuàng)建的 Hello.say 函數(shù)
Hello.say()
end
end
注意我們 defmodule 用Mix.Tasks
開頭蚕涤,后接我們想在命令里執(zhí)行任務(wù)時(shí)用的名字筐赔。第二行用 use Mix.Task
把 Mix.Task
這個(gè) behaviour 引入當(dāng)前命名空間。然后定義一個(gè)忽略所有參數(shù)的 run 函數(shù)揖铜。在這個(gè)函數(shù)里調(diào)用hello
module 里的say
函數(shù)川陆。
Mix 任務(wù)實(shí)戰(zhàn)
來看看我們的 Mix 任務(wù)。首先保證在命令行中我們處在這個(gè)任務(wù)能起作用的目錄蛮位,然后敲 mix hello
,我們應(yīng)該會(huì)看到下面的結(jié)果:
$ mix hello
Hello, World!
當(dāng)你打錯(cuò)字鳞绕, Mix 會(huì)用字符串模糊匹配來給你推薦:
$ mix hell
** (Mix) The task "hell" could not be found. Did you mean "hello"?
不知道你有沒有注意到我們剛剛用了一個(gè)新的模塊屬性(module attribute)失仁?就是 @shortdoc
,這個(gè)屬性在我們發(fā)布應(yīng)用的時(shí)候非常有用们何,比如一個(gè)用戶在命令行里敲 mix help
的時(shí)候萄焦。
$ mix help
mix app.start # Starts all registered apps
...
mix hello # Simply calls the Hello.say/0 function.
...