Getting A Grip on GridFS

I know it is almost Christmas and your minds are beginning to turn to gifts and family, but hang with me for a few more minutes. My buddy Jon pointed me to Grip yesterday. I liked the idea but not all of the implementation. I’ve been doing some GridFS stuff lately so I decided to take some time and tweak it to be more what I need.

The main changes I made were to store name, size and content_type along with the path to the file. I also made it so those are assigned when the file is set so that they can be used in validations. Some other ideas I have for the plugin are adding image resizing with MojoMagick and common validations (much like most of the file upload plugins out there).

What I really like about Grip is its simplicity. A single, small file, an include, a call to has_grid_attachment, and you can start storing files. The great thing about working on this is it gave me some wonderful ideas for how to standardize the process of creating and declaring MongoMapper plugins.

I’ll be adding those to ideas to MongoMapper over the next few weeks as I get time and I think people are going to be stoked about what I’ve come up with (thanks to Brandon for brainstorming the plugin API with me).

Behind the Scenes

As I said, behind the scenes, Grip uses GridFS (more on GridFS), Mongo’s specification for storing files in Mongo.

The good news is that the API for storing files in GridFS using Ruby is nearly identical to using Ruby’s File class. Unfortunately, that is also the bad news, in my opinion, as I find Ruby’s File open, read and close a bit awkward. Here are a few examples pulled almost directly from Grip:

14 Comments

Would it make more sense to use a nested object instead of underscore notation? Such as, in your example, foo.image would return a nested document with name, content_type, size, and path keys? If we have the ability to nest objects, it seems like we should make the most of it!

We’re looking to attach email files from in memory to our mongo mapper document. The problem is that since they are not files, we need to write them to temporary files to allow grip to read from them. Is there a better way to make this work without having to write to a temporary file?

neither image_content_type nor image_path are in the current codebase of grip. this should be changed/updated in this poting! furthermore the method image_id exists, which returns the gridfs-object-id to correctly serve the file to the client. john, can you update your posting?
regards, m

Sorry, comments are closed for this article to ease the burden of pruning spam.

About

Authored by John Nunemaker (Noo-neh-maker), a web developer and programmer who has fallen deeply in love with Ruby. More about John.