4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Elixir Module attributes

Posted at

Elixir Module attributes

概要

Elixir の Module attributes について。

Module Attributes の役割

  • ユーザーやVMに知らせるアノテーション情報
  • 定数
  • 一時保存

ユーザーやVMに知らせるアノテーション情報

VMのコンパイル前後へのフックの設定や、
ドキュメンテーション用の情報などを設定できる。
ドキュメントは ExDoc で出力可能です。

具体的なアノテーションには

  • @after_compile : モジュールのコンパイル後のフック
  • @doc : function, macro のドキュメンテーションコメント用
  • @moduledoc : module のドキュメンテーションコメント用

などがあります。

詳しくは公式ドキュメントの Module の attributes 参照。
Module

サンプルコード

@on_definition アノテーションを試してみます。

defmodule Hook do
  def on_def(_env, kind, name, args, guards, body) do
    IO.puts "kind: #{kind}"
    IO.puts "name: #{name}"
    IO.puts "guards: "
    IO.inspect guards
    IO.puts "args: "
    IO.inspect args
    IO.puts "body: "
    IO.puts Macro.to_string(body)
  end
end

defmodule HookUser do
  @on_definition {Hook, :on_def}

  def hoge(msg) do
    IO.puts msg
  end

  def hoge_with_guard(list) when is_atom(list) or is_list(list) do
    IO.inspect list
  end
end

出力

kind: def
name: hoge
guards:
[]
args:
[{:msg, [line: 17], nil}]
body:
IO.puts(msg)
kind: def
name: hoge_with_guard
guards:
[{:__op__, [line: 21],
  [:orelse,
   {{:., [], [:erlang, :is_atom]}, [line: 21], [{:list, [line: 21], nil}]},
   {{:., [], [:erlang, :is_list]}, [line: 21], [{:list, [line: 21], nil}]}]}]
args:
[{:list, [line: 21], nil}]
body:
IO.inspect(list)

定数

サンプルコード

defmodule Months do
  @january 1
  @february 2
  @march 3
  @april 4
  @may 5
  @june 6
  @july 7
  @august 8
  @september 9
  @october 10
  @november 11
  @december 12

  def months, do: [@january, @february, @march, @april, @may, @june, @july, @august, @september, @october, @november, @december]
end

IO.inspect Months.months

出力

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

一時保存

下記ページ参照
As temporary storage

参照

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?