Skip to content

Instantly share code, notes, and snippets.

@nowk
Forked from felipeelias/paperclip_initializer.rb
Created January 11, 2011 00:12
Show Gist options
  • Save nowk/773762 to your computer and use it in GitHub Desktop.
Save nowk/773762 to your computer and use it in GitHub Desktop.
Paperclip initializer to provide dimensions data for the original attachment
# width & height attributes for the original image only
# since style dimensions are already known
#
# Migration to add width & height attribtues for the original attachment
#
# add_column :<model>, :<attachment>_file_width, :integer
# add_column :<model>, :<attachment>_file_height, :integer
#
#
# class Document < ActiveRecord::Base
# # paperclip
# #
# has_attached_file :file, :styles => { :medium => "300x300>" }
#
# before_save :save_dimensions
#
# def save_dimensions
# # file.dirty? helps the app from hanging when updating with no new file
# if file.dirty? && file.image?
# geom = Paperclip::Geometry.from_file(file.queued_for_write[:original])
# file.width = geom.width
# file.height = geom.height
# end
# end
# end
#
#
# doc = Document.create :file => <an image>
# doc.file.width #=> returns a number
# doc.file.height #=> returns a number
#
# TODOs
# * Real-time geometry if the width & height are not originally set
# * Push `save_dimensions` callback into Paperclip so we don't have to set it all the time
# * allow `is_image?` to work off of provided content_types
# * Clear `:file_width` & `:file_height` attributes when an attachment has no dimensions or is cleared
module Paperclip
class Attachment
def width
instance_read(:file_width)
end
def height
instance_read(:file_height)
end
def width=(val)
instance_write(:file_width, val)
end
def height=(val)
instance_write(:file_height, val)
end
def is_image?
content_type =~ %r{^(image|(x-)?application)/(png|pjpeg|jpeg|jpg|png|gif)$}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment