Serve GridFS Files Directly From Rack.
Kimono is using Carrierwave to handle image attachments and save them into GridFS - MongoDB’s built-in filesystem. GridFS is great because you get the benefits of MongoDB’s replication and sharding. Putting files into GridFS is pretty straight forward, and we won’t waste time getting into that here, Jeremy Weiland has written an excellent post on using Rails 3, Carrierwave and GridFS which does a great job of covering off the specifics of getting the three pieces of software to talk nicely together. One thing that immediately jumped out at us was the fact that Jeremy’s Rails Metal controller reads the entire file contents into RAM before sending it back to the client:
Rather than go his route we decided to monkey patch Mongo::GridIO to respond to the each method, which is required by the Rack API:
Next we can use the Rails 3 router’s ability to pass in a proc to use directly as a rack handler to respond to the request while bypassing as much of the rails stack as possible:
So now the GridFS file is streamed chunk-by-chunk to the client without storing the contents of the file in RAM on the way. Also, with a small modification this file can be moved directly to a rackup file and used directly by a rack enabled web servers such as passenger:
We hope we’ve given you a good overview of how insanely great Rack is, and how easy it is to use GridFS from within Rack. Yay for us.