How to load all Erlang modules in a directory automatically?
Asked Answered
D

2

6

Using the answer from Easy way of loading projects with rebar dependencies, dependencies are now automatically resolved, but they are not automatically loaded.

So, how can I load all the modules in my ebin and /deps/*/bin path automatically? That way they are available when using the Erlang shell tab completion, which speeds up my dev process considerably.

My solution based on the great answer of Adam Lindberg: https://gist.github.com/1131312 It will only load the project modules automagically, so almost no delay in erl startup.

Drava answered 3/8, 2011 at 8:16 Comment(0)
N
10

This snippet would do the trick:

[code:ensure_loaded(list_to_atom(filename:rootname(filename:basename(F))))
 || P <- code:get_path(), F <- filelib:wildcard(P ++ "/*.beam")].

Put it in your ~/.erlang file as one row (including the dot: .) and it will be executed upon starting any Erlang shell. Be warned though, it's hideously slow!

» time erl -noshell -s init stop
erl -noshell -s init stop  0.11s user 0.02s system 11% cpu 1.143 total # Without
» time erl -noshell -s init stop
erl -noshell -s init stop  7.31s user 1.08s system 88% cpu 9.480 total # With 
Neuralgia answered 3/8, 2011 at 13:15 Comment(2)
Tnx, I'm happy to trade in some upfront performance for convenience.Drava
Yeah, auto-loading of the module upon the first TAB press would be cool. :-)Neuralgia
L
6

if you spawn the process, you will get a very fast start.

LP = fun() -> [code:ensure_loaded(list_to_atom(filename:rootname(filename:basename(F)))) || P <- code:get_path(), F <- filelib:wildcard(P ++ "/*.beam")] end.
spawn(LP).

in the ~/.erlang file

Lyso answered 4/8, 2013 at 7:33 Comment(2)
@VansS To make sure the shell can autocomplete module and function names when pressing Tab.Neuralgia
@Adam Lindberg Right. In the scope of this particular question using ensure_loaded this way makes sense.Bashuk

© 2022 - 2024 — McMap. All rights reserved.