Retrieving the height and width attributes of image thumbnails in Rails with attachment_fu
Wednesday, October 8th, 2008The problem:
All of the examples I could find of how to display images with attachment_fu in Rails look like this:
image_tag(my_photo.public_filename(:small))
I programmed a complete website with this kind of code before I realized that I really need to include height and width attributes in my image tags. The attachment object has height and width attributes… but in the example above, where I’m displaying the :small thumbnail of an image, I couldn’t find a way, via the API, to retrieve the small image version in order to query its height and width.
If there’s something obvious I’ve missed, please let me know! At any rate, here’s an example page from Green Fabric, the site where I’m doing this. Obviously, with this many images, having the height and width is critical. And I’ve seen a huge difference in the perceived and actual page loading times after making my change.
My solution:
I’m new to Ruby, so I’m sure there’s a much smoother way of doing this, but here’s what I’ve written. First, my new view template code to display the image in the example above would look like this:
photo_tag(my_photo, "small")
And the tag will include the correct height and width attributes. Now comes the part where it’s clear that I’m not a Ruby expert. I’m sure I could have done this by somehow mixing in new code into the attachment_fu library… but I don’t know how to do that. So I created a couple of helper methods, which is what photo_tag is. This code is from application_helper.rb:
def thumbnail_for(full_size_image, thumbnail_name)
full_size_image.thumbnails.each do |i|
return i if i['thumbnail'] == thumbnail_name
end
return nil
end
def photo_tag(photo, thumbnail_name=nil, css_class=nil)
if thumbnail_name.nil?
image = photo
else
image = thumbnail_for(photo, thumbnail_name)
end
if css_class.nil?
return image_tag(image.public_filename, :size=>image.image_size)
else
return image_tag(image.public_filename, :size=>image.image_size, :class=>css_class)
end
end
