From: Joel VanderWerf Date: 2012-01-26T05:13:28+09:00 Subject: Re: [ANN] "files" gem - for creating temporary files and dirs On 01/24/2012 12:03 PM, Alex Chaffee wrote: > Ever want to create a whole bunch of files at once? Like when you're > writing tests for a tool that processes files? The Files gem lets you > cleanly specify those files and their contents inside your test code, > instead of forcing you to create a fixture directory and check it in > to your repo. It puts them in a temporary directory and cleans up when > your test is done. > > The API currently has two modes -- mixin and function -- and I would > absolutely adore feedback on which mode is more useful, or other > advice about naming the methods and especially the instance var in > mixin mode. > > Usage (mixin mode): > > require "files" > include Files > > file "hello.txt" # creates file "hello.txt" containing > "contents of hello.txt" > > dir "web" do # creates directory "web" > file "snippet.html", # creates file "web/snippet.html"... > "

Fix this!

" # ...containing"

Fix this!

" > dir "img" do # creates directory "web/img" > file File.new("data/hello.png") # containing a copy > of hello.png > file "hi.png", File.new("data/hello.png") # and a copy of > hello.png named hi.png > end > end Here's another way to do it. (FSDB does a lot of other stuff, too...) require 'fsdb' # gem install fsdb require 'tmpdir' data = FSDB::Database.new "data" formats = [ FSDB::TEXT_FORMAT.when(/\.txt$|\.html$/), FSDB::BINARY_FORMAT.when(/\.png$/) ] data.formats = formats Dir.mktmpdir do |dir| #dir = "tmp1" # for testing, use a dir that won't be deleted tmp = FSDB::Database.new(dir) tmp.formats = formats tmp["hello.txt"] = "contents of hello.txt" tmp["web/snippet.html"] = "

Fix this!

" img = tmp.subdb("img") img["hello.png"] = data["hello.png"] img["hi.png"] = data["hello.png"] end # you can automatically serialize objects in yaml, json, or marshal: require 'yaml' require 'json' Dir.mktmpdir do |dir| #dir = "tmp2" # for testing, use a dir that won't be deleted tmp = FSDB::Database.new(dir) json_format = FSDB::Format.new( /\.json$/, /\.js$/, :name => "JSON_FORMAT", :load => proc {|f| JSON.load(f)}, :dump => proc {|object, f| f.syswrite(JSON.dump(object))} ) tmp.formats = formats + [FSDB::YAML_FORMAT, json_format] tmp["a.yaml"] = {:some => ["complex", Object]} tmp["b.json"] = ["foo", 2, 3] end