1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-04 23:58:01 +00:00

Add Refer To A Module Within Itself as an elixir til

This commit is contained in:
jbranchaud
2019-03-18 13:36:54 -05:00
parent e0c786c045
commit 10b1ab273b
2 changed files with 31 additions and 1 deletions

View File

@@ -0,0 +1,29 @@
# Refer To A Module Within Itself
Elixir comes with the `__MODULE__` reserve word for referencing a module
within itself. This is handy for things like structs.
```elixir
defmodule SomeNamespace.MyModule do
defstruct [:id]
def do_thing(%__MODULE__{}=thing) do
# ...
end
end
```
You can use an alias in order to ditch `__MODULE__` and perhaps make your
code a bit more human readable.
```elixir
defmodule SomeNamespace.MyModule do
alias __MODULE__, as: MyModule
defstruct [:id]
def do_thing(%MyModule{}=thing) do
# ...
end
end
```