In Ruby it's really handy to store static text after __END__
for arbitrary use via the DATA
IO object:
puts DATA.read # Prints "This is the stuff!"
__END__
This is the stuff!
However, when I try to reference the DATA object from the context of a new class I get unexpected errors (in Ruby 1.9.3 and 2.0, apparently):
class Foo
STUFF = DATA.read # <class:Foo>: uninitialized constant Foo::DATA (NameError)
end
class Foo
STUFF = ::DATA.read # <class:Foo>: uninitialized constant DATA (NameError)
end
Any idea how I could make this work?
There are already comments, that the error can't be confirmed, Babai also posted working examples.
Maybe you have another problem:
DATA corresponds to the text after __END__
of the main document, not the actual source code file.
It works:
class Foo
STUFF = DATA
p STUFF.read
end
__END__
This is the stuff!
Here the source code file and the main file is the same.
But if you store it as test_code.rb
and load it in a main file:
require_relative 'test_code.rb'
Then you get the error:
C:/Temp/test_code.rb:2:in `<class:Foo>': uninitialized constant Foo::DATA (NameError)
from C:/Temp/test_code.rb:1:in `<top (required)>'
from test.rb:1:in `require_relative'
from test.rb:1:in `<main>'
If your main file is again
require_relative 'test_code.rb'
__END__
This is the stuff!
Then the process works with the output This is the stuff!
To answer your question:
__END__
in a library, only as part of the main file.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With