1. Computing

Embedding Images in Gosu Programs


2 of 4

How It Works

At the end of every Ruby file, you're able to provide data that isn't part of the script. Anything after the line reading __END__ is treated as data, and isn't parsed by the Ruby interpreter. This data can be read like a file by using the DATA variable. However, it's not quite as easy as dumping the file's data into this section.

First, you shouldn't put binary data in a file people open with text editors. This generally makes a mess of people's screens, and the data will get mangled when the text editor tries to interpret line endings in the binary section. So, to start off, we need to encode this binary data in Base64. This is so called "ascii armor" and will protect this binary data from text editors.

Second, in order to store more than one file in this section, we need a way of referring to different parts of the data section. We're going to use YAML here, as it comes with Ruby and it's simple to use.

At the beginning of any program that uses this data, there's a line that reads $data = YAML.parse(DATA.read). This will parse the YAML stored in the DATA section, ready to be used from the $data global variable. Global variables are usually frowned upon, but since this is really designed for small, self-sufficient scripts, there's no reason not to use one here.

Finally, a small method is needed to turn these data sections into real files. The with_data method will decode the Base64-encoded data and write it to a temporary file, then pass the filename of that temporary file to a given block. It's not the most efficient way of doing things, but it will work with any code that expects a file.

This article is part of a series. Read more articles about Rapid Game Prototyping in Ruby

  1. About.com
  2. Computing
  3. Ruby
  4. Tutorials
  5. Rapid Game Prototyping with Gosu
  6. How It Works

©2014 About.com. All rights reserved.