DATA.readlines in an inner file

B

Bill Guindon

Is there any way to use DATA.readlines to read the data (below
__END__) in a file that's been required/included? I want the read
code to be inside the included/required file.
 
A

ara.t.howard

Is there any way to use DATA.readlines to read the data (below
__END__) in a file that's been required/included? I want the read
code to be inside the included/required file.

i don't think one can do it directly, but:


harp:~ > cat b.rb
require 'dynaload'

module M
def your_code_here_as_normal
end
end


#
# add this to the end of the file
#
data = open(__FILE__)
data.each{|line| break if line =~ /^__END__$/}
Dynaload::export data, "name" => "DATA"

__END__
42



harp:~ > cat a.rb
require 'dynaload'

loaded = Dynaload::dynaload "b.rb"

obj, desc = loaded.objects.select{|obj, desc| desc['name'] == 'DATA'}.first

puts obj.read



harp:~ > ruby a.rb
42

regards.

-a
 
B

Bill Guindon

i don't think one can do it directly, but:

Thanks much, was hoping there was a more elegant solution. I was just
going to use it to avoid a 'here doc' block. Now, the 'here doc'
doesn't look so bad ;)
harp:~ > cat b.rb
require 'dynaload'

module M
def your_code_here_as_normal
end
end


#
# add this to the end of the file
#
data =3D open(__FILE__)
data.each{|line| break if line =3D~ /^__END__$/}
Dynaload::export data, "name" =3D> "DATA"

__END__
42



harp:~ > cat a.rb
require 'dynaload'

loaded =3D Dynaload::dynaload "b.rb"

obj, desc =3D loaded.objects.select{|obj, desc| desc['name'] =3D=3D = 'DATA'}.first

puts obj.read



harp:~ > ruby a.rb
42

regards.

-a
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,668
Latest member
SamiraShac

Latest Threads

Top