Elixir Macro - How it save time & keep code clean for us

Mạnh Vũ - Feb 26 - - Dev Community

Intro

I have worked with macro (meta-programming) in C, Delphi & Erlang language but with Elixir it is different, meta-programming in Elixir is really fun & useful.

You can made a DSL style like Plug and Ecto library in your code if you want it isn't hard.

For us, we call rpc in Elixir cluster so much. In regular way we can call directly to rpc function in :erpc module (Erlang module) but this way is not convenience because: The first we need code a separated function or module to handle rpc call. The second we always need to find target node to call. And more, if we have a ton of nodes that has same function (for HA & scale out) that is painful for dev is not good about distributed computing.

For reduce time & also support scale out, I made a wrapper module for rpc call, then other devs just need to use with some options and use same way with local function. Our wrapper module also support change name of target function just by declare in config file.

This is very efficient way for us, add rpc just in seconds. Every complex thing is behind the scene.

I will show how I made this.

How I use macro

In config file of project user need to declare like:

config :my_app, :my_rpc,
   node_list: [...], # or {mod, fun, args}
   module: RemoteModule,
   funtion_list: [
     {:function_1, 1},
     {:funtion_2, :new_name, 0}
   ]
Enter fullscreen mode Exit fullscreen mode

In local module dev need use my module with config option (and other options if needed). When compiling macro will inject to local module with function name in config (target name or new name) then local module or other modules can call rpc look like local function.

local module example:

defmodule ModA
use RpcHelper, otp_app: :my_app, config: :my_rpc
end

# usage
ModA.function_1("hello")
Enter fullscreen mode Exit fullscreen mode

Dev can have several remote modules in same app if needed.

So with macro we can cut down a lot of duplicated code and make it easy for dev who not friendly with distributed system.

I also provided basic technique for select target node for better scalable and HV.

Conclusion

This way help us so much, reduced time for write call rpc code, keep our code clean and easy to maintain!

In the near future, we will bring this to open source library for community can use or get an example to do similar task.

. . . . . . . . . . . . . . . . . . . .