What I've learned today - 4 - Elixir - Executing a code after load

lgdev07

Luan Gomes

Posted on May 6, 2021

What I've learned today - 4 - Elixir - Executing a code after load

Quick tip

Executing code Immediately after loading a Module

Elixir has @on_load which accepts atom as function name in the same module or a tuple with function_name and its arity like {function_name, 0}.

Examples

#Hello module 
defmodule Hello do
@on_load :onload     # this executes after module gets loaded 
  def onload do
    IO.puts "#{__MODULE__} is loaded successfully"
  end
end
# Execution .... Just copy and paste the code in the iex terminal
# You will see the output something like this ....
Elixir.Hello is loaded successfully  
{:module, Hello,
 <<70, 79, 82, 49, 0, 0, 4, 72, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0, 0, 130,
   0, 0, 0, 12, 12, 69, 108, 105, 120, 105, 114, 46, 72, 101, 108, 108, 111, 8,
   95, 95, 105, 110, 102, 111, 95, 95, 9, ...>>, {:onload, 0}}
Enter fullscreen mode Exit fullscreen mode

Alt Text

Obtained from: https://github.com/blackode/elixir-tips

I appreciate everyone who has read through here, if you guys have anything to add, please leave a comment.

đź’– đź’Ş đź™… đźš©
lgdev07
Luan Gomes

Posted on May 6, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related