两个文件,a.rb和b.rb
当a.rb中有__END__表示的注释,并且需要通过DATA关键字来获得的时候,
如果直接执行a.rb,也就是当$0和__FILE__为同一文件对象时,
DATA可以读取到a.rb中__END__后面的内容.
如果a.rb被b.rb调用执行,
比如b.rb中load "a.rb",
这样a.rb中的DATA其实是b.rb中的对象,所以DATA只能得到b.rb中的__END__之后的内容.
一直很期待能有个解决方法让a.rb不论如何执行都可以得到本身的DATA对象,
但问了核心开发组,结果Ruby他爸Matz说没办法.
那我只能把本来写在__END__后面的内容单独写到一个模板文件中,然后然a.rb读取这个文件对象当作DATA对象了.
引用
Charles Cui 发送至 ruby-core
显示详细信息 15:33 (18 小时前)
how to get global constant DATA in file <a.rb>,if a.rb is loaded by b.rb.
when b.rb is exec by Ruby,even if the DATA is used in a.rb,infact the DATA is from b.rb,
because a.rb is loaded by b.rb.
how to resolve it?
such as:
<b.rb> :
Cui$ cat /usr/local/ruby-1.8.7-p160/bin/roadrunner
#!/usr/local/ruby-1.8.7-p160/bin/ruby
#
# This file was generated by RubyGems.
#
# The application 'roadrunner' is installed as part of a gem, and
# this file is here to facilitate running it.
#
require 'rubygems'
version = ">= 0"
if ARGV.first =~ /^_(.*)_$/ and Gem::Version.correct? $1 then
version = $1
ARGV.shift
end
gem 'roadrunner', version
load Gem.bin_path('roadrunner', 'roadrunner', version)
<a.rb>
#this is code
__END__
#!/usr/bin/env ruby
#main.rb
#this is the DATA
回复
转发
回复所有人
Charles Cui 发送至 ruby-core
显示详细信息 15:33 (18 小时前)
- 显示引用文字 -
回复
转发
回复所有人
Yukihiro Matsumoto 发送至 ruby-core
显示详细信息 15:56 (18 小时前)
Hi,
In message "Re: [ruby-core:30175] [Problem] DATA and __END__ in a loaded rb file"
on Wed, 12 May 2010 16:33:57 +0900, Charles Cui <[email protected]> writes:
|how to get global constant DATA in file <a.rb>,if a.rb is loaded by b.rb.
|when b.rb is exec by Ruby,even if the DATA is used in a.rb,infact the DATA
|is from b.rb,
|because a.rb is loaded by b.rb.
DATA is only available from the script file.
matz.
回复
转发
回复所有人
Urabe Shyouhei 发送至 ruby-core
显示详细信息 17:29 (16 小时前)
(2010/05/12 16:56), Yukihiro Matsumoto wrote:
> DATA is only available from the script file.
True, but I know the reporter's feeling. Ruby stops parsing at __END__ even on
a library file so it's natural for a programmer to expect DATA be file local.
Can there be any future addition of DATA[__FILE__] or something like that?
回复
转发
回复所有人
Magnus Holm 发送至 ruby-core
显示详细信息 17:35 (16 小时前)
Right now you'll have to do something like:
data = File.read(__FILE__) =~ /^__END__\n/ && $' || ''
// Magnus Holm
- 显示引用文字 -