Skip to content

Instantly share code, notes, and snippets.

@maxschulze
Forked from lawitschka/photo.rb
Created November 30, 2010 11:21
Show Gist options
  • Save maxschulze/721540 to your computer and use it in GitHub Desktop.
Save maxschulze/721540 to your computer and use it in GitHub Desktop.
Save image size for paperclip photo
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