From 10b1ab273b53c98156f043850fcf9146b89fe3e5 Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Mon, 18 Mar 2019 13:36:54 -0500 Subject: [PATCH] Add Refer To A Module Within Itself as an elixir til --- README.md | 3 ++- elixir/refer-to-a-module-within-itself.md | 29 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 elixir/refer-to-a-module-within-itself.md diff --git a/README.md b/README.md index eea587a..ddaa937 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_786 TILs and counting..._ +_787 TILs and counting..._ --- @@ -148,6 +148,7 @@ _786 TILs and counting..._ - [Pattern Matching In Anonymous Functions](elixir/pattern-matching-in-anonymous-functions.md) - [Quitting IEx](elixir/quitting-iex.md) - [Range Into List Using Comprehensions](elixir/range-into-list-using-comprehensions.md) +- [Refer To A Module Within Itself](elixir/refer-to-a-module-within-itself.md) - [Referencing Values In IEx's History](elixir/referencing-values-in-iexs-history.md) - [Remove One List From Another](elixir/remove-one-list-from-another.md) - [Replace Duplicates In A Keyword List](elixir/replace-duplicates-in-a-keyword-list.md) diff --git a/elixir/refer-to-a-module-within-itself.md b/elixir/refer-to-a-module-within-itself.md new file mode 100644 index 0000000..271d14f --- /dev/null +++ b/elixir/refer-to-a-module-within-itself.md @@ -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 +```