Skip to content

Instantly share code, notes, and snippets.

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 Empact/484876 to your computer and use it in GitHub Desktop.
Save Empact/484876 to your computer and use it in GitHub Desktop.
# Filename: RAILS_ROOT/lib/paperclip_processors/thumbnail_with_dimensions.rb
# Required Configuration in the model
# has_attached_file :image,
# :styles => {
# :thumbnail => {
# :geometry => "100x100>",
# :format => :png,
# :processors => [:thumbnail_with_dimensions],
# :mystyle => :thumbnail
# },
# :some_other_style => {
# :geometry => "640x480>",
# :processors => [:thumbnail_with_dimensions],
# :mystyle => :some_other_style
# }
# }
#
# NOTE: Since the name of the style isn't available in the processor we need to pass it in using a configuration variable.
# I've called it :mystyle just to make sure I don't step on anything in the core.
#
# 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)
Integer(dimensions[style.to_s]['width']) rescue nil
end
def height(style = :original)
Integer(dimensions[style.to_s]['height']) rescue nil
end
def dimensions
@dimensions ||= begin
dim = instance_read(:dimensions)
JSON.parse(dim) unless dim.nil?
end
end
end
end
module Paperclip
class ThumbnailWithDimensions < Thumbnail
def initialize(file, options = {}, attachment = nil)
super
@myinstance = attachment
@mystyle = options[:mystyle]
@dimensions = attachment.dimensions
end
def make
dst = super
@dimensions ||= {} # make sure he have a hash
@dimensions[@mystyle] = Geometry.from_file dst
# make sure the original dimensions are saved since we don't actually process the original
@dimensions[:original] ||= @current_geometry
@myinstance.instance_write(:dimensions, @dimensions.to_json)
return dst
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment