LoginSignup
3
3

More than 5 years have passed since last update.

[Elixir]ファイルの自動生成を行うカスタムタスクを作成する

Last updated at Posted at 2015-08-23

Goal

ファイルの自動生成を行うカスタムタスクを作成する。

Dev-Environment

OS: Windows8.1
Erlang: Eshell V6.4, OTP-Version 17.5
Elixir: v1.0.4

Wait a minute

mixのコマンドからファイルを自動生成させる一例です。

Index

My mix command
|> Preparation
|> Automatic generation of file

Preparation

準備は以下の記事を見て下さい。
前の記事: Mixのカスタムタスクを作成する

Automatic generation of file

mixのコマンドからファイルの自動生成を行うカスタムタスクを作成します。

ファイル: lib/mix/tasks/sample.ex

defmodule Mix.Tasks.Sample do
  use Mix.Task
  import Mix.Generator

  @shortdoc "My custom task sample"

  def run(_args) do
    app_module = Mix.Project.config[:app] |> Atom.to_string |> Mix.Utils.camelize
    assigns = [app_module: app_module]

    # template
    create_file(
      Path.join(["lib", "test_template.ex"]) |> Path.relative_to(Mix.Project.app_path),
      test_template(assigns))

    # text
    create_file(
      Path.join(["lib", "test.ex"]) |> Path.relative_to(Mix.Project.app_path),
      test_text)
  end

  # template
  embed_template :test, """
  defmodule <%= @app_module %>.Test do
  end
  """

  # text
  embed_text :test, """
  defmodule MyMixCmd.Test do
  end
  """
end

Result:

>mix sample
* creating lib/test_template.ex
* creating lib/test.ex

Description:

embed_template/2で渡している引数内の@app_module部分は、
assignsの内容に変換されて出力されています。

Phoenix-Frameworkでよく使う、
.html.eexの埋め込みコードのようなことをやっていますね。
実際にこれEExの機能です。

embed_text/2は、渡している引数の通り出力されていますね。

Speaking to oneself

Mix.Generator.embed_template/2を使う場合、
Mix.Generator.create_file/3の第二引数に渡す値がさっぱり分からなかった。

お陰様で大分時間を消費してしまった。

Bibliography

Github - ma2gedev/breadcrumble_ex implement generator for the Phoenix application
A Custom Mix Task for Phoenix App
hexdocs - v1.0.5 Elixir Mix
hexdocs - v1.0.5 Elixir Mix.Task
hexdocs - v1.0.5 Elixir Mix.Generator
hexdocs - v1.0.5 Elixir Mix.Utils
hexdocs - v1.0.5 Elixir Mix.Project

3
3
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
3
3