ShiftEleven

Useless Ruby Tricks: DATA and __END__

So maybe not totally useless certainly fun. Normally, ruby scripts are finished when you reach the end of a file; however, this is not always the case. You can end your script sooner by using the __END__ keyword in your script. Once added, everything you type after that will not be parsed by ruby.

So what?

Well, you can use the global variable DATA to get the contents of what you wrote after the __END__ block. DATA is actually a File object to just that piece of text in your script.

How about a little sample to make things a little clearer?

#!/usr/bin/env ruby
%w(yaml pp).each { |dep| require dep }

obj = YAML::load(DATA)

pp obj

__END__
---
-
  name: Adam
  age: 28
  admin: true
-
  name: Maggie
  age: 28
  admin: false

So with this, I was able to embed a little bit of YAML directly into my script. I added the YAML after __END__. YAML::load will accept a File object, so I just passed it DATA and now I have a reconstituted array.

Maybe that's not the most practical use of this information; however, Sinatra provides a really awesome use of this.  With Sinatra, you can create a whole web application that lives in one single, solitary ruby file.  Sinatra can use in-file templates.  In-file templates are added into the space after __END__ where each view file is annotated with @@view_name.

require 'rubygems'
require 'sinatra'

get '/' do
  haml :index
end

__END__

@@ layout
%html
  = yield

@@ index
%div.title Hello world!!!!!

Not bad for a useless trick!

Comments

comments powered by Disqus