author | Mahlon E. Smith <mahlon@martini.nu> |
Sat, 22 Jan 2011 01:55:55 -0800 | |
branch | ruby-modules |
changeset 8 | fe38422c10a4 |
parent 2 | e5c705047540 |
permissions | -rw-r--r-- |
1
9e127bf6e84f
Initial commit of chunker, a ruby module to aid with data blocks.
mahlon
parents:
diff
changeset
|
1 |
|
2 | 2 |
Preface: |
3 |
||
4 |
Ruby provides an automatic constant called DATA, which is an IO object |
|
5 |
that references all text in the current file under an __END__ token. |
|
6 |
||
7 |
I find it convenient to use the __END__ area to store all sorts of |
|
8 |
stuff, rather than have to worry about distributing separate files. |
|
9 |
||
10 |
||
11 |
The problem: |
|
12 |
||
13 |
The DATA constant is determined from whatever ruby believes $0 to be. |
|
14 |
It doesn't work inside of other required libraries, so you'll see stuff |
|
15 |
like this all the time: |
|
16 |
||
17 |
END = File.open( __FILE__ ).read.split( /^__END__/, 2 ).last |
|
18 |
||
19 |
It works, but it's more work than I want to do. |
|
20 |
||
21 |
||
22 |
A workaround: |
|
23 |
||
24 |
Chunker solves this by parsing __END__ tokens for you, and making it |
|
25 |
available in the form of a 'DATA_END' constant. It installs this |
|
26 |
constant into the class that includes Chunker, so you can use it again |
|
27 |
and again, assuming you use a different file for each class. |
|
1
9e127bf6e84f
Initial commit of chunker, a ruby module to aid with data blocks.
mahlon
parents:
diff
changeset
|
28 |
|
2 | 29 |
It also automatically parses out other things that look like tokens, so |
30 |
you can easily have multiple, distinct documents all embedded into the |
|
31 |
__END__ block. |
|
32 |
||
33 |
||
34 |
Usage: |
|
35 |
||
36 |
There is no direct interface to Chunker. Just include it from a |
|
37 |
class to have that file's __END__ data blocks magically become DATA_* |
|
38 |
IO constants within that class. |
|
39 |
||
40 |
||
41 |
Example: |
|
42 |
||
43 |
This produces the string "Yep.\n". |
|
1
9e127bf6e84f
Initial commit of chunker, a ruby module to aid with data blocks.
mahlon
parents:
diff
changeset
|
44 |
|
2 | 45 |
|
46 |
require 'chunker' |
|
47 |
class Foom |
|
48 |
include Chunker |
|
49 |
end |
|
50 |
||
51 |
puts Foom.new.class.const_get( :DATA_WICKED ).read |
|
1
9e127bf6e84f
Initial commit of chunker, a ruby module to aid with data blocks.
mahlon
parents:
diff
changeset
|
52 |
|
2 | 53 |
__END__ |
54 |
Stuff in the END block! |
|
55 |
__WOW__ |
|
56 |
Ultimate success! |
|
57 |
__WICKED__ |
|
58 |
Yep. |
|
59 |