Embed Directive in Elixir

Here’s the translation of the Go code to Elixir, along with explanations in Markdown format suitable for Hugo:

Elixir doesn’t have a direct equivalent to the //go:embed directive, but we can achieve similar functionality using Elixir’s built-in File module and application environment variables. Here’s how we can approach this:

defmodule EmbedExample do
  # Read file contents at compile time
  @external_resource "folder/single_file.txt"
  @file_string File.read!("folder/single_file.txt")

  # Read file contents as binary
  @file_binary File.read!("folder/single_file.txt")

  # Simulate embedding multiple files
  @folder_files Path.wildcard("folder/*.hash")
               |> Enum.map(&{Path.basename(&1), File.read!(&1)})
               |> Enum.into(%{})

  def run do
    # Print out the contents of 'single_file.txt'
    IO.puts(@file_string)
    IO.puts(@file_binary)

    # Retrieve some files from the embedded folder
    IO.puts(Map.get(@folder_files, "file1.hash"))
    IO.puts(Map.get(@folder_files, "file2.hash"))
  end
end

In this Elixir version:

  1. We use module attributes and the @external_resource attribute to read file contents at compile time. This is similar to embedding files in the binary.

  2. @file_string and @file_binary represent the contents of single_file.txt as a string and binary respectively.

  3. @folder_files simulates embedding multiple files by reading all .hash files in the folder directory and storing them in a map.

  4. The run/0 function demonstrates how to access and use the “embedded” file contents.

To run this example, you would first need to create the necessary files:

$ mkdir -p folder
$ echo "hello elixir" > folder/single_file.txt
$ echo "123" > folder/file1.hash
$ echo "456" > folder/file2.hash

Then you can run the Elixir script:

$ elixir embed_example.exs
hello elixir
hello elixir
123
456

Note that this approach reads the files at compile time, which is similar to embedding files in the binary. However, the files still need to exist at runtime, unlike true file embedding. For a more robust solution in a production environment, you might want to consider using Elixir’s release system, which can include static assets in the release.