Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I refer to DATA in class context?

Tags:

ruby

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?

like image 576
maerics Avatar asked Jan 13 '23 12:01

maerics


1 Answers

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:

  • You can't use __END__ in a library, only as part of the main file.
  • Use Here-documents instead - or store your data in an external data file.
like image 108
knut Avatar answered Jan 25 '23 03:01

knut