javascript - OO Style Arguments in Elixir? -
how can pass self parameter in elixir in oo way?
for example wrote erlang javascript object garbage collection:
-module(o). -export([n/0, g/2, s/3, d/1]). -behaviour(gen_server). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(state, {dictionary=dict:new()}). -define(server, ?module). -on_load(deps/0). deps() -> = fun(mod) -> try application:start(mod) catch _type:_what -> ok end end, [as(mod) || mod <- [sasl, lager, resource]], ok. n() -> case gen_server:start(?module, {}, []) of {ok, pid} -> res = resource:notify_when_destroyed(pid, {timeout, pid}), {?module, {res, pid}}; other -> other end. g(key, {?module, {_res, pid}}) -> gen_server:call(pid, {g, key}). s(key, val, {?module, {_res, pid}}) -> gen_server:cast(pid, {s, key, val}). d({?module, {_res, pid}}) -> gen_server:cast(pid, stop). %% @private init({}) -> {ok, #state{}}. %% @private handle_call({g, key}, _from, state = #state{dictionary=dict}) -> {reply, case dict:find(key, dict) of {ok, val} -> val; error -> error end, state}; handle_call(request, _from, state) -> lager:info("handle_call discarded request: ~p", [request]), {reply, {error, unknown_call}, state}. %% @private handle_cast({s, key, value}, state = #state{dictionary=dict}) -> {noreply, state#state{dictionary=dict:store(key, value, dict)}}; handle_cast(stop, state) -> {stop, normal, state}; handle_cast(msg, state) -> lager:info("handle_cast discarded message: ~p", [msg]), {noreply, state}. %% @private handle_info({timeout, pid}, state) -> d({?module, {res, pid}}), lager:info("garbage collection of object ~p", [pid]), {noreply, state}; handle_info(info, state) -> lager:info("handle_info discarded message: ~p", [info]), {noreply, state}. %% @private terminate(_reason, _state) -> ok. %% @private code_change(_oldvsn, state, _extra) -> {ok, state}.
note: use https://github.com/tonyrog/resource.git resource collection.
1> l(o). ... logs ... {module,o} 2> o = o:n(). {o,{{resource,140524043665312,<<>>},<0.58.0>}} 3> o:s(a, b). ok 4> o:g(a). b 6> o:s(hello, fun() -> io:format("hello world~n") end). ok 7> (o:g(hello))(). hello world ok
as far i'm aware it's not possible call modules in way in elixir. must explicitly pass self parameter of calls. take erlang example elixir, like:
iex> o = o.n() {o, {{:resource, 140524043665312, <<>>}, <0.58.0>}} iex> o.s(:a, :b, o) :ok iex> o.g(:a, o) :b ...
someone else can chime in , correct me here, haven't seen oo-like access demonstrated here in of elixir code i've seen.
Comments
Post a Comment