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?
1#!/usr/bin/env ruby
2%w(yaml pp).each { |dep| require dep }
3
4obj = YAML::load(DATA)
5
6pp obj
7
8__END__
9---
10-
11 name: Adam
12 age: 28
13 admin: true
14-
15 name: Maggie
16 age: 28
17 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
.
1require 'rubygems'
2require 'sinatra'
3
4get '/' do
5 haml :index
6end
7
8__END__
9
10@@ layout
11%html
12 = yield
13
14@@ index
15%div.title Hello world!!!!!
Not bad for a useless trick!
Comments
comments powered by Disqus