Skip to main content

Command Palette

Search for a command to run...

#16: What the __MODULE__ ?

Published
•2 min read•View as Markdown
#16: What the __MODULE__ ?
S

I am a full-stack developer from Austria who has studied and worked in many countries including the UK, Australia, and the US. I have worked extensively with Ruby on Rails, React, and Typescript, and I am also building projects using Elixir and Phoenix.

In Elixir, the __MODULE__ macro is a special construct that is used to refer to the current module in which it is used. It is a compile-time construct that gets replaced with the name of the module during compilation. This allows you to reference the current module dynamically without hardcoding the module name.

Here are some Key points about the __MODULE__ macro:

  1. Dynamic Module Reference: When you use __MODULE__ within a module, it gets replaced with the name of the module at compile time. This is particularly useful when you need to reference the current module in function definitions, module attributes, or other parts of the code.

  2. Avoid Hardcoding: Using __MODULE__ helps in avoiding hardcoding the module name, which can make the code more maintainable and flexible. If the module name changes, you don't need to update all references manually.

  3. Example Usage:

defmodule MyModule do
  def print_module_name do
    IO.puts("Current module: #{__MODULE__}")
  end
end

MyModule.print_module_name()

In the example above, __MODULE__ is used to dynamically print the name of the current module (MyModule) when the print_module_name function is called.

  1. Limitations: It's important to note that __MODULE__ is a compile-time construct and is resolved during compilation. This means that if you dynamically generate module names at runtime, __MODULE__ will not work as expected.

Overall, __MODULE__ is a convenient macro in Elixir that allows you to refer to the current module dynamically, making your code more flexible and easier to maintain.

More from this blog

Stephan Yu's Tech Journal

28 posts

This is my space for writing about tech-related topics that I find interesting. It allows me to share the things I have learned with the world.