问题描述
我有2个ruby源文件,例如:
A.rb
require "B"
foo
B.rb
def foo()
..
end
现在我使用代码将A编译为字节码(Ruby v2.3.3):
byte_code = RubyVM::InstructionSequence.compile_file "A.rb"
File.binwrite "A.byte",byte_code.to_binary
当我运行字节码时:
byte_code_in_binary = IO.binread "A.byte"
instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code_in_binary
instruction_from_byte_code.eval
当时的消息是:
.... in `require': cannot load such file -- B (LoadError)
如果我将B.rb编译为字节码,那么A.byte如何加载B.byte?还是有另一种方式将整个ruby项目编译为字节码并运行? Jruby或某些工具可以实现它吗?谢谢。
解决方法
暂时解决的问题。答案是:创建一个“代码外壳”以加载二进制文件,看起来像:
filelist.rb
def write_code(fname,load_filename)
str =
'byte_code_in_binary = IO.binread("'+load_filename+'")
instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code_in_binary
instruction_from_byte_code.eval'
f = open(fname,"wb")
f.write(str)
f.close()
end
$LOAD_PATH.unshift(File.dirname(__FILE__))
require "filelist"
Dir.mkdir($folder)
byte_code = RubyVM::InstructionSequence.compile_file $main_entry
File.binwrite $folder + "/some_binary_file_name",byte_code.to_binary
$required_files.each do |f|
write_code($folder + "/" + f,some_required_binary_names)
byte_code = RubyVM::InstructionSequence.compile_file f
File.binwrite $folder + "/" + some_required_binary_names,byte_code.to_binary
end
现在正在编译源代码,它看起来像:
byte_code_in_binary = IO.binread("file_1_binary_name") <-- it was real compiled binary file_1.rb
instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code_in_binary
instruction_from_byte_code.eval
确定,现在需要ruby脚本文件如下:
file_1.rb
<meta name="viewport" content="width=device-width,initial-scale=1.0">
现在我们可以使用“ VM二进制模式”加载需求文件。