How to create global variables in Erlang

Adil picture Adil · Jan 6, 2010 · Viewed 17.1k times · Source

I am writing an ejabberd module to filter packets. I need to get the hostname to pull some configs using gen_mod:get_module_opt().

I have 4 important functions :

  1. start(Host, _Opt) : This is an ejabberd function to load my module. I get the Host atom here
  2. filter_packet({From, To, XML}): This is my packet filter hook. I cannot pass custom params to this function, as it is a hook in ejabberd.
  3. get_translation(XmlData): filter_packet() calls get_translation() in a loop
  4. fetch_translation(XmlData): called recursively from get_translation(). This is where I am calling gen_mod:get_module_opt(), and hence need the Host.

My question is, how can I take Host from start() and put it in a global variable, so that fetch_translation can access it?

Answer

Zed picture Zed · Jan 6, 2010

The "easiest way" is to create a named ets table, and put it in there.

start(Host, _Opt) ->
  ets:new(my_table, [named_table, protected, set, {keypos, 1}]),
  ets:insert(my_table, {host, Host}),
  ...

fetch_translation(XmlData) ->
  [{_, Host}] = ets:lookup(my_table, host),
  ...

Note that this is a "general" solution. Ejabberd might provide facilities for what you want, but I cannot help you with that.