📜 ⬆️ ⬇️

Adding to_string simplifies development and debugging code on Elixir

Let's check on an example: we write a service with airports and destinations.

defmodule Airport do defstruct [:id, :name] end defmodule Direction do defstruct [:origin, :destination] def example do madrid = %Airport{id: "MAD", name: "Madrid"} riga = %Airport{id: "RIX", name: "Riga"} %Direction{origin: riga, destination: madrid} end end 

So far, everything is in order. Great, we ate a cookie, see what's next in jire. List of the most popular destinations?


')
First, we make a small test list and get an unreadable sheet:

 popular = Enum.map(1..5, fn _ -> Direction.example end) # => # [%Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}, # %Direction{destination: %Airport{id: "MAD", name: "Madrid"}, # origin: %Airport{id: "RIX", name: "Riga"}}] 

Add a pinch of readability:

 defimpl String.Chars, for: Airport do def to_string(airport) do "#{airport.name} (#{airport.id})" end end defimpl String.Chars, for: Direction do def to_string(direction) do "#{direction.origin}#{direction.destination}" end end 

And we get a clear neat conclusion:

 Enum.each(popular, fn(x) -> IO.puts(x) end) # => # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD) # Riga (RIX) → Madrid (MAD) 

Now seriously


Sometimes when developing you need to analyze the contents of variables. The internal presentation is accurate, but not always readable. In such cases, you can teach Elixir to translate your structures into strings. To do this, define the function to_string as part of the implementation of the String.Chars protocol.

As an additional bonus, interpolation will start to work automatically. Without the implementation of the to_string for airports this would not work:

 "#{direction.origin}#{direction.destination}" 

That's all. Readable code!

Source: https://habr.com/ru/post/328208/


All Articles