LoginSignup
13
0

More than 1 year has passed since last update.

今日のElixirSchoolメモ16「カスタムMixタスク」

Posted at

Elixir Schoolの学習メモです。

セットアップ

$ mix new hello
* creating README.md
* creating .formatter.exs
* creating .gitignore
* creating mix.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 に "Hello, World!"を出力する簡単な関数を作成する。

defmodule Hello do
  @doc """
  Outputs `Hello, World!` every time.
  """
  def say do
    IO.puts("Hello, World!")
  end
end

カスタムMixタスク

カスタムのMixタスクを作成する。
新しいディレクトリとファイル、 hello/lib/mix/tasks/hello.ex を作成する。

defmodule Mix.Tasks.Hello do
  @moduledoc "The hello mix task: `mix help hello`"
  use Mix.Task

  @shortdoc "Simply calls the Hello.say/0 function."
  def run(_) do
    # calling our Hello.say() function from earlier
    Hello.say()
  end
end

アプリケーションの読み込み

Mixはアプリケーションやその依存関係を自動的に起動しない。
ただ、Ectoを使用してDBとやりする必要がある場合は、Ecto.Repoの起動を確認する必要がある。
処理する方法は2つあり、明示的にアプリを起動する、もしくはプリケーションを起動して他のアプリ達も起動する方法である。

defmodule Mix.Tasks.Hello do
  @moduledoc "The hello mix task: `mix help hello`"
  use Mix.Task

  @shortdoc "Simply calls the Hello.say/0 function."
  def run(_) do
    # This will start our application
    Mix.Task.run("app.start")

    Hello.say()
  end
end

Mixタスクの実行

$ mix hello
Compiling 1 file (.ex)
Hello, World!
13
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
0