1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Embedding Images in Gosu Programs


3 of 4

The Rakefile
Embedding Images in Gosu Programs

The following Rakefile is provided to automatically compile all images from a directory into a Base64-encoded YAML file ready for use. In addition, it can also insert it directly into your script, replacing everything after the __END__ line with this Yaml data.

There are two Rake tasks you can use.

  • rake compile[directory] - This will take all the PNG files in a directory and create a Yaml file from them. It'll simply print this Yaml file out on the terminal. You can pipe it to a file, or copy and paste it into your script.
  • rake insert[directory,script.rb] - This Rake task is a bit more useful. It will compile the same Yaml file as above, but instead of printing it to the terminal, it will insert it into the script you passed in the parameters. It will read the script in, replace everything after the __END__ line with the Yaml file.

require 'base64'
require 'yaml'
require 'tempfile'
require 'fileutils'

def compile_directory(dir)
 store = {}

 Dir["#{dir}/*.png"].each do|png|
    File.open(png, "rb") do|f|
     b64 = Base64.encode64(f.read)
     store[File.basename(png)] = b64


task :compile, [:directory] do |t, args|
 puts compile_directory(args.directory).to_yaml

task :insert, [:directory, :file] do|t, args|
 store = compile_directory(args.directory)

 Tempfile.open('Rakefile') do|tmp|
    File.open(args.file) do|file|
       line = file.gets.chomp
     end until line == "__END__"
    FileUtils.mv( tmp.path, args.file )

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

  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. Rapid Game Prototyping with Gosu
  6. The Rakefile

©2014 About.com. All rights reserved.