Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you parameterize a gen_server module?

Tags:

erlang

EDIT:

I'm not looking to use parameters as a general purpose way to construct Erlang programs--I'm still learning the traditional design principles. I'm also not looking to emulate OOP. My only point here is to make my gen_server calls consistent across server instances. This seems more like fixing a broken abstraction to me. I can imagine a world where the language or OTP made it convenient to use any gen_server instance's api, and that's a world I want to live in.

Thanks to Zed for showing that my primary objective is possible.


Can anyone figure out a way to use parameterized modules on gen_servers? In the following example, let's assume that test_child is a gen_server with one parameter. When I try to start it, all I get is:

42> {test_child, "hello"}:start_link().
** exception exit: undef
     in function  test_child:init/1
        called as test_child:init([])
     in call from gen_server:init_it/6
     in call from proc_lib:init_p_do_apply/3

Ultimately, I'm trying to figure out a way to use multiple named instances of a gen_server. As far as I can tell, as soon as you start doing that, you can't use your pretty API anymore and have to throw messages at your instances with gen_server:call and gen_server:cast. If I could tell instances their names, this problem could be alleviated.

like image 742
mwt Avatar asked Aug 14 '09 20:08

mwt


1 Answers

I just want to say two things:

  • archaelus explains it correctly. As he says the final way he shows is the recommended way of doing it and does what you expect.

  • never, NEVER, NEVER, NEVER use the form you were trying! It is a left over from the old days which never meant what you intended and is strongly deprecated now.

like image 67
rvirding Avatar answered Sep 19 '22 13:09

rvirding