Unfortunately, the DATA
global constant is set when the "main" script is loaded. A few things that might help:
You can at least get A_DATA
to be correct. Just reverse the order of the first two operations in a.rb
:
# a.rb
A_DATA = DATA.read
require 'b'
...
You can get the B_DATA
to be correct if you go through a bit of rigamarole:
# load_data_regardless_of_main_script.rb
module LoadDataRegardlessOfMainScript
def self.from(file)
# the performance of this function could be
# greatly improved by using a StringIO buffer
# and only appending to it after seeing __END__.
File.read(file).sub(/\A.*\n__END__\n/m, '')
end
end
# b.rb:
require 'load_data_regardless_of_main_script'
B_DATA = LoadDataRegardlessOfMainScript.from(__FILE__)