DEV Community

Mạnh Vũ
Mạnh Vũ

Posted on

Solve alias problem in Elixir

Recently, I must type too much for alias Module for using short name in code(Module name in Elixir is quite long). Problem here is I need to repeat that action over and over.

When posted a proposal for solve this problem I receives an advice very valuation from community. I repost the idea in here for people can read and solve problem if that problem is like mine.

Define a macro and function for supporting centric all aliases like:

defmodule Namespace do @moduledoc """ This module provides a way to define a namespace for a set of modules. It can be used to define a set of modules that share a common prefix. This version only support for native atom not a alias. # usage ``` use Namespace, DataSpace ``` """ defmacro __using__(namespace) do Namespace.get(Macro.expand_once(namespace, __ENV__)) end def get(Suppliers) do quote do alias MyApp.Domains.Suppliers alias Suppliers.Hotel alias Suppliers.Transport alias Suppliers.Restaurant end end def get(Customers) do quote do alias MyApp.Structs.Customers alias Customers.Address alias Customers.Details end end end 
Enter fullscreen mode Exit fullscreen mode

In other module I can use like:

defmodule MyApp.Data.Processor do use Namespace, Suppliers ... end 
Enter fullscreen mode Exit fullscreen mode

This way help me provide a centric way and clean code for alias and avoid to repeat add alias ... action.

Downside of this way is compiler is warning if an alias is unused.

Original idea is from post in Elixir community

Top comments (0)