Skip to content

Instantly share code, notes, and snippets.

@lawitschka
Created November 30, 2010 11:20
Show Gist options
  • Save lawitschka/721537 to your computer and use it in GitHub Desktop.
Save lawitschka/721537 to your computer and use it in GitHub Desktop.
Automatically retrieving and caching image sizes of processed images in Paperclip. Dependencies: * typed_serialize (http://github.com/jqr/typed_serialize) If you do not want to use typed_serialize, make sure to initialize an empty Hash in cache_ima
class Photo < ActiveRecord::Base
has_attached_file :image, :styles => { :thumb => ['150x150#', :png],
:normal => ['660x660', :png] },
:default_style => :normal
typed_serialize :sizes, Hash
before_save :cache_image_sizes
# Get size of this photo for specified style
#
# Returns a string of the schema "{Width}x{Height}"
def size(style = image.default_style)
style = style.to_sym
size = self.sizes[style]
end
private
def cache_image_sizes
self.image.styles.each do |style_name, style|
self.sizes[style_name] = Paperclip::Geometry.from_file( self.image.to_file(style_name) ).to_s
end
return true
end
end
module PhotosHelper
def image_tag(source, options = {})
unless source.is_a?(Photo)
super(source, options)
else
options = options.symbolize_keys
style = options.has_key?(:style) ? options.delete(:style).to_sym : source.image.default_style
super(source.image.url(style), {:size => source.size(style)}.merge(options))
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment