Gistからrequireする方法
Gist
はちょっとしたコードの切れ端を貼付けておくのに便利です。
先日紹介したEndless RubyのコードもGist上でのみ公開されていました。
Gemを作るまでもないコードをGistに貼付けて、そのままrequireして使えると便利そうだと思ったので、試してみました。
ruby>>
module Gist
module_function
def require(id, sha1 = "HEAD")
Kernel.require "open-uri"
gist = "http://gist.github.com"
eval(if sha1 == "HEAD"
open("#{gist}/#{id}.txt").read
else
Kernel.require "tmpdir"
cache = File.join(Dir.tmpdir, "gist-#{id}-#{sha1}")
if File.exist?(cache)
open(cache).read
else
open("#{gist}/raw/#{id}/#{sha1}") do |i|
code = i.read
open(cache, "w"){|o| o.write code}
code
end
end
end)
end
end
Gist.require("148479", "a59ea9ec3e865bafd1e4413b43b6ccb7a38d76fc")
#=> Hello, world!
<<--
Hash値で内容の変更が検出可能なので、md5のチェックサムを信用している人にとっては同程度の安全性で利用できそうです。