Embed Directive in Crystal

Here’s the translation of the Go code example to Crystal, formatted in Markdown suitable for Hugo:

Our first example demonstrates how to embed files and folders into the Crystal binary at compile time. Crystal doesn’t have a direct equivalent to Go’s embed directive, but we can achieve similar functionality using macros and the File class.

# Import the necessary standard library modules
require "file"

# Define a macro to read file contents at compile time
macro read_file(filename)
  {{ File.read(filename) }}
end

# Read the contents of a single file into a string
file_string = read_file("folder/single_file.txt")

# Read the contents of a single file into a byte array
file_byte = File.read("folder/single_file.txt").to_slice

# Create a hash to store multiple files
folder = {
  "folder/file1.hash" => read_file("folder/file1.hash"),
  "folder/file2.hash" => read_file("folder/file2.hash")
}

# Main function
def main
  # Print out the contents of `single_file.txt`
  print file_string
  print String.new(file_byte)

  # Retrieve some files from the embedded folder
  content1 = folder["folder/file1.hash"]
  print content1

  content2 = folder["folder/file2.hash"]
  print content2
end

main

In this Crystal example, we use a macro read_file to read file contents at compile time. This achieves a similar effect to Go’s embed directive. We then demonstrate how to read file contents into a string and a byte slice, and how to create a hash to store multiple files.

To run this example, you’ll need to create the necessary files and folders:

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

Then you can compile and run the Crystal program:

$ crystal build embed_example.cr
$ ./embed_example
hello crystal
hello crystal
123
456

This example demonstrates how to embed file contents into your Crystal program at compile time, which can be useful for including configuration files, templates, or other resources directly in your binary.