Thumbnails – or avatars – are a standard part of many web apps. Paperclip has made things super easy for active record and datamapper. Here is how I accomplished similar – but basic – thumbnail generation for couchdb. The end solution is RESTful, good for my needs, and hopefully good for your needs too.
You should know that couchdb supports inline attachments and I opted for that route rather than store the images in a file folder like paperclip does. I felt this was more inline with the couchdb way of doing things.
Begin by installing mini_magick
1 sudo gem install mini_magick
1 sudo gem install mini_magickOr add mini_magick to dependencies.rb
1 dependency "mini_magick", "1.2.5"
1 dependency "mini_magick", "1.2.5"
I’m using Merb. The setup for rails would be to use config.gem mini_magick I believe.Setup the view
Place the avatar uploading mechanism in it’s own form. Use the /users/update_avatar POST action to process the thumbnails.
Setup the users.rb update_avatar POST action and route
The update_avatar action will process the ‘avatar’ image file using the custom ‘update_avatar_images’ method. If you are on rails, you will have to pass params[:avatar] here.
Additionally, the avatar route/action is defined in users.rb also. This will allow us to display the thumbnails restfully via /user/scottmotte/avatar & /user/scottmotte/avatar?style=mini
Furthermore, you will see that my validation is not in the model as it ideally should be. I haven’t figured out how to tackle this yet based on how the couchdb attachments work inline as an array.
Setup the user.rb model to process the thumbnails
Rather than pick out the little pieces of the user.rb model that are related to the update_avatar action in users.rb I’m just posting the entire model.
The key method to examine is the update_avatar_images and it’s cousin resize_and_crop – which resizes the uploaded avatar to a square.
The strange AppConfig array I am using there is from my config/app_config/settings.yml file from merbjedi’s merb_app_config. It looks like this the following but you could just as easily define your own array or list each upload separately.
The put_attachment method is from couchrest and puts the images to the couchdb user document.
Now when a user uploads an avatar image, it creates an inline original.png, thumb.png, and mini.png. And the are accessible via /users/scottmotte/avatar?style=mini
That’s how I did things. Let me know if you have a better way. A gem would be ideal. Maybe I’ll morph this into a gem if I find myself repeating it enough.
![]()
Spitfire Sky | github | archives | resume