關鍵字和預定義變量:__END__和DATA的問題

兩個文件,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對象了.


[quote]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 小時前)
- 顯示引用文字 -
回覆
轉發
回覆所有人
[color=red]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.[/color]

回覆
轉發
回覆所有人
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
- 顯示引用文字 -[/quote]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章