Skip to content

Instantly share code, notes, and snippets.

@aanand
Created December 9, 2008 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aanand/33885 to your computer and use it in GitHub Desktop.
Save aanand/33885 to your computer and use it in GitHub Desktop.
# Hook for storing the dimensions of uploaded images.
#
# Use like this:
#
# class MyModel
# has_attached_file :image, :styles => { :thumb => '72x72#' }
#
# stores_dimensions :image
# end
#
# You can now access the width and height using MyModel#image_width and MyModel#image_height.
module Paperclip
module ClassMethods
def stores_dimensions name
property "#{name}_width".to_sym, Integer
property "#{name}_height".to_sym, Integer
define_method "#{name}_image?" do
!!self.send("#{name}_content_type").match('^image/')
end
before :save do
if self.send("#{name}?") and self.send("#{name}_image?")
attachment = self.send(name)
attribute_set("#{name}_width".to_sym, attachment.width)
attribute_set("#{name}_height".to_sym, attachment.height)
end
end
end
end
class Attachment
def width(style = default_style)
Paperclip::Geometry.from_file(to_file(style)).width
end
def height(style = default_style)
Paperclip::Geometry.from_file(to_file(style)).height
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment