Guest User

ruby bytecode convert

a guest
Mar 29th, 2013
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.19 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. # encoding: UTF-8
  3.  
  4. # info: compile ruby code in file.rb into bytecode and save it compressed as file.rbo
  5. #       or load bytecode from compressed file.rbo and run it when an .rbo file is the input
  6. # usage: script file.rb
  7. #        script file.rbo
  8. # requirements: ruby version >= 1.9
  9.  
  10. require 'zlib'
  11.  
  12.  
  13. # check ruby version
  14. (puts "error: minimum ruby version of 1.9"; exit 1) if RUBY_VERSION < "1.9.0"
  15.  
  16. # check file argument
  17. (puts "error: file argument missing (ruby source file.rb or bytecode compiled file.rbo)"; exit 1) if ARGV.size < 1
  18.  
  19. # get file name
  20. myfile = ARGV[0]
  21.  
  22. # file exists?
  23. (puts "error: file #{myfile} does not exist"; exit 1) if not File.exist? myfile
  24.  
  25. # get file extension
  26. myext = myfile.scan(/\.[^\.]*$/)[0]
  27.  
  28.  
  29. # file is bytecode or plain source?
  30. if    myext == ".rb"
  31.     code = RubyVM::InstructionSequence.compile_file(myfile).to_a
  32.     File.write("#{myfile}o", Zlib::Deflate.deflate(Marshal.dump(code)))
  33.  
  34. elsif myext == ".rbo"
  35.     code = Marshal.restore((Zlib::Inflate.inflate(File.read(myfile))))
  36.     RubyVM::InstructionSequence.load(code).eval
  37.  
  38. else
  39.     puts "error: file type must be a ruby source file.rb or a ruby compiled bytecode file.rbo"
  40.     exit 1
  41. end
Advertisement
Add Comment
Please, Sign In to add comment