Created
March 22, 2013 10:51
-
-
Save armanm/5220451 to your computer and use it in GitHub Desktop.
Paperclip doesn't give you image dimensions. I saw a bunch of different implementations and didn't like em. So I rolled my own. This implementation will save the `width` and `height` of images to the model in which you define your `has_attachmented_file` field.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# this migration allows to have polymorphic models | |
class CreateAssets < ActiveRecord::Migration | |
def self.up | |
create_table :assets, :force => true do |t| | |
t.string :type | |
t.integer :assetable_id | |
t.string :assetable_type | |
t.string :attachment_file_name | |
t.string :attachment_content_type | |
t.integer :attachment_file_size | |
t.integer :width | |
t.integer :height | |
t.timestamps | |
end | |
end | |
def self.down | |
drop_table :assets | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# stick this inside the inialization directory or if you | |
# append this to your Paperclip initialization file if you | |
# have one already | |
module Paperclip | |
class Attachment | |
def image?(style = default_style) | |
to_file(style).image? | |
end | |
def temp_file_location(style = default_style) | |
to_file(style).path | |
end | |
alias :old_assign :assign | |
def assign(uploaded_file) | |
old_assign(uploaded_file) | |
set_dimension_fields(uploaded_file.path) | |
end | |
def set_dimension_fields(path) | |
return unless image? | |
dims = Paperclip::Geometry.from_file(File.open(path)) | |
instance.send("width=" , dims.width ) | |
instance.send("height=", dims.height) | |
end | |
end | |
module Upfile | |
def image? | |
["image/jpeg", "image/tiff", "image/png", "image/gif", "image/bmp"].include?(content_type) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment