Today I Learned

hashrocket A Hashrocket project

Run an Elixir function on Module load

If you want to run a function on Module load, you can turn to Modules @on_load hook.

#hello_world.ex
defmodule Example do
  @on_load :hello_world

  def hello_world do
    IO.puts("Hello World!")
    :ok
  end
end
$ elixir hello_world.ex
Hello World!

Your function must return :ok otherwise the module load will be aborted.

Using @on_load can be an efficient way to run examples, quick scripts, setup requirements, benchmarking or load in libraries from other languages.

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.