为什么我不能在类上下文中引用DATA?
在Ruby中,在__END__
之后存储静态文本以便通过DATA
IO对象进行任意使用非常方便:
puts DATA.read # Prints "This is the stuff!" __END__ This is the stuff!
但是,当我尝试从新类的上下文中引用DATA对象时,我得到了意外错误(显然在Ruby 1.9.3和2.0中):
class Foo STUFF = DATA.read # : uninitialized constant Foo::DATA (NameError) end class Foo STUFF = ::DATA.read # : uninitialized constant DATA (NameError) end
知道我怎么能做这个工作吗?
已经有评论,错误无法确认,巴拜也发布了工作实例。
也许你有另一个问题:
DATA对应于主文档__END__
之后的文本,而不是实际的源代码文件。
有用:
class Foo STUFF = DATA p STUFF.read end __END__ This is the stuff!
这里的源代码文件和主文件是相同的。
但是如果将它存储为test_code.rb
并将其加载到主文件中:
require_relative 'test_code.rb'
然后你得到错误:
C:/Temp/test_code.rb:2:in `': uninitialized constant Foo::DATA (NameError) from C:/Temp/test_code.rb:1:in `' from test.rb:1:in `require_relative' from test.rb:1:in `'
如果您的主文件是再次
require_relative 'test_code.rb' __END__ This is the stuff!
然后这个过程与输出一起工作这就是东西!
回答你的问题:
- 您不能在库中使用
__END__
,仅作为主文件的一部分。 - 请使用Here-文档 – 或将数据存储在外部数据文件中。
好博客在这里: – Useless Ruby Tricks: DATA and END
这是如何工作:
class Foo def dis DATA.read end end Foo.new.dis # => "This is the stuff!\n" __END__ This is the stuff!
class Foo STUFF = DATA p STUFF.read end __END__ This is the stuff! # >> "This is the stuff!\n"
RUBY_VERSION # => "2.0.0" class Foo p STUFF = DATA.read end __END__ This is the stuff! # >> "This is the stuff!\n"
我倾向于使用File.read(__FILE__).split("\n__END__\n", 2)[1]
而不是DATA.read