📎 Webclip
Converting Erlang code into Elixir
The post walks through a direct conversion of a Cowboy WebSocket example from Erlang to Elixir. It focuses on the simplest translation path, not on idiomatic Elixir, and points out places where Erlang syntax and Elixir syntax can look similar but behave differently.
Reading notes#
- Creates a
ws_cowboyproject and says four files need to be changed or added:mix.exs,lib/ws_cowboy.ex,lib/ws_handler.ex, andlib/ws_supervisor.ex - Copies the
privdirectory from the Cowboy example into the project root - Adds the Cowboy dependency in
mix.exsand configures the OTP application module asWsCowboy - In
ws_cowboy.ex, defines the application behaviour, builds Cowboy routes, starts the HTTP server, and startsWsSupervisor - Explains that Erlang module references become
:<module_name>in Elixir and that lowercase names in Erlang are atoms, so they become atoms with a colon in Elixir - Notes that Erlang uppercase names are variables, so they are changed to lowercase during conversion
- Warns that a single-quoted
'_'in Erlang must become:_in Elixir, or Cowboy will compile and run but return 400 responses - Says function calls are transcribed by replacing
:with. - In
ws_handler.ex, keeps the WebSocket handler behaviour, upgrades the HTTP request, starts timers, replies to text messages, and ignores other events - Says Elixir can use normal double-quoted strings and string interpolation where the Erlang version used binary notation
- In
ws_supervisor.ex, uses__MODULE__instead of Erlang?MODULE - Says the server is run with
mix run --no-haltand viewed athttp://127.0.0.1:8080 - Concludes that the translation is straightforward but requires attention to small syntax differences, and mentions that idiomatic Elixir would use the Elixir supervisor instead of the Erlang one
