Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wpeterson/827827 to your computer and use it in GitHub Desktop.
Save wpeterson/827827 to your computer and use it in GitHub Desktop.
# Filename: RAILS_ROOT/config/initializers/paperclip_thumbnail_with_dimensions.rb
# Required Configuration in the model
#
# include Paperclip::Dimensions
#
# has_attached_file :image,
# :styles => {
# :thumbnail => {
# :geometry => "100x100>",
# :format => :png
# },
# :some_other_style => {
# :geometry => "640x480>"
# }
# }
#
# after_post_process :save_image_dimensions
#
# To get a dimension in a view just do:
# <%= @object.image.width(:thumbnail) %> # Gives the width of the thumbnail
# <%= @object.image.height(:thumbnail) %> # Gives the height of the thumbnail
# <%= @object.image.width %> # Gives the width of the original
# <%= @object.image.dimensions %> Will return the dimensions hash
module Paperclip
class Attachment
def width style = :original
@dimensions ||= dimensions
Integer(@dimensions[style.to_s]['width']) rescue nil
end
def height style = :original
@dimensions ||= dimensions
Integer(@dimensions[style.to_s]['height']) rescue nil
end
def dimensions
@dimensions ||= JSON.parse(dim) if dim = instance_read(:dimensions)
end
end
end
module Paperclip::Dimensions
def save_image_dimensions
attachments = []
self.attributes.each do |attr|
attr_match = attr[0].match(/(.*)_file_name/)
attr_name = attr_match[1] if attr_match
if attr_match && self.respond_to?(attr_name)
potential = self.send attr_name
attachments << potential if potential.instance_of? Paperclip::Attachment
end
end
# Event may be fired once per attachment, but I'm not sure how to distinguish
attachments.each do |attachment|
dimensions = attachment.dimensions || {} # make sure he have a hash
attachment.styles.each do |style_prop|
style = style_prop[0]
dimensions[style] = Paperclip::Geometry.from_file(attachment.queued_for_write[style])
end
# once for the original
dimensions[:original] = Paperclip::Geometry.from_file(attachment.queued_for_write[:original])
attachment.instance_write(:dimensions, dimensions.to_json)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment