Loading ruby source from a zip archive?

泪湿孤枕 提交于 2019-12-24 08:46:12

问题


I have a mod_rails server where disk space, oddly enough, is at a premium. Is there a way for me to compress my application's source, like Python's zipimport?

There are obvious disadvantages to this, so I should probably just break down and spend a nickel on disk space, but I figured it'd be worth a shot.


回答1:


Oh, this is neat. Check out the rubyzip gem:

rubyzip also features the zip/ziprequire.rb module (source) which allows ruby to load ruby modules from zip archives.

(Update: The ziprequire.rb is no longer present in the rubyzip gem, but the source link appears to contain its old content nonetheless.)

Like so. This is just slightly modified from their example:

require 'rubygems'
require 'zip/zipfilesystem'
require 'zip/ziprequire'

Zip::ZipFile.open("/tmp/mylib.zip", true) do |zip|
  zip.file.open('mylib/somefile.rb', 'w') do |file|
    file.puts "def foo"
    file.puts "  puts 'foo was here'"
    file.puts "end"
  end
end

$:.unshift '/tmp/mylib.zip'
require 'mylib/somefile'

foo    # => foo was here

You don't have to use the rubyzip library to create the zipped library, of course. You can use CLI zip for that.




回答2:


require and load are just methods like any other. You can undefine them, redefine them, override them, hook them, wrap them to do anything you want. In fact, that's exactly how RubyGems works.

Now, I don't know whether someone has already implemented this for you, but I actually remember some discussions about this on the ruby-talk mailinglist.

However, there are some examples of loading library code from alternative locations that you can look at, and maybe copy / adapt what they are doing for your purpose:

  • http_require does pretty much what it sounds like: it allows you to require an HTTP URI
  • Crate is a Ruby packaging tool which packages a Ruby application into a single binary and a couple of SQLite databases; it modifies require to load libraries out of an (encrypted) SQLite database instead of the filesystem
  • and of course I already mentioned RubyGems


来源:https://stackoverflow.com/questions/2069073/loading-ruby-source-from-a-zip-archive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!