Tuesday, January 15, 2008

Reloading all code from the Erlang shell

One of the reasons Erlang is pretty cool is that it supports hot code reloading. With OTP (Open Telecom Platform) applications, this can be done through a complicated mechanism involving release files, code_change callbacks to update state, and special upgrade/downgrade scripts.

In development, however, that's a bit of a nuisance. So, how do you simply reload all of the loaded modules after you've recompiled them? Here's a quick solution to paste into your ~/.erlang:


Reload = fun(M) ->
code:purge(M),
code:soft_purge(M),
{module, M} = code:load_file(M),
{ok, M}
end.

ReloadAll =
fun() ->
Modules = [M || {M, P} <- code:all_loaded(), is_list(P) andalso string:str(P, "/home/amiest") > 0],
[Reload(M) || M <- Modules]
end.


Obviously, replace /home/amiest with a directory within which your modules reside. Then, simply run ReloadAll(). from the shell to load the newest versions of your modules.

2 comments:

Jay Doane said...

Unfortunately, I'm unable to get this to work. The code seems fine, and there is no complaint when my ~/.erlang file is loaded when the shell starts. However, in the shell when I try to execute it, I get:

1> ReloadAll().
* 1: variable 'ReloadAll' is unbound

Any ideas?

Todd said...

Hi Jay,

Check our blog for a post a little bit more recent that defines the la() function. It's probably a better thing to use.

-Todd