20 April 2008 Manfred Stienstra and Eloy Duran

In Smalltalk code and data are always kept together. In Ruby this isn’t the case. Manfred looks at a poor man’s version of keeping your data with your code.

Download episode

continue.rb

require 'base64'

class Continue
  def self.freeze(data)
    code = File.read($0).gsub(/\n^__END__.*$/m, '')
    File.open($0, 'w') do |file|
      file.write(code)
      file.write("\n__END__\n")
      file.write(Base64.encode64(Marshal.dump(data)))
    end
  end
  def self.defrost
    Marshal.load(Base64.decode64(DATA.read)); rescue NameError
  end
end

notes.rb

#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/continue'

class Notes
  def initialize
    @lines = []
  end
  
  def add(line)
    @lines << line
  end
  
  def list
    puts @lines.join("\n") unless @lines.empty?
  end
end

if __FILE__ == $0
  notes = Continue.defrost || Notes.new
  if ARGV.empty?
    notes.list
  else
    notes.add(ARGV.join(' '))
  end
  Continue.freeze(notes)
end