Sha256: a432fb12e26025b770ba87501e3e03d9e79b11821f99ecc2c8438e8b6600d226

Contents?: true

Size: 1.79 KB

Versions: 1

Compression:

Stored size: 1.79 KB

Contents

require 'paperclip'

module Paperclip
  module Dimension
    def self.included(klass)
      klass.extend Paperclip::Dimension::ClassMethods
    end

    module ClassMethods
      # override has_attached_file to:
      # 1). save dimensions on post process
      # 2). create dimension accessors
      def has_attached_file name, options={}
        super

        class_eval <<-END
          # for ActiveRecord
          serialize :#{name}_dimensions, Hash if respond_to?(:serialize)

          def #{name}_dimension(style=:original)
            self.#{name}_dimensions[style.to_s]
          end

          def #{name}_dimension_str(style=:original)
             dim = #{name}_dimension(style.to_s)
             dim ? dim.join('x') : nil
          end
        END

        send "after_#{name}_post_process", lambda { save_dimensions_for(name) }
      end
    end

    def save_dimensions_for(name)
      dimension_hash = {}
      attachment = self.send(name)
      return unless attachment.content_type =~ %r{^(image|(x-)?application)/(bmp|gif|jpeg|jpg|pjpeg|png|x-png)$}
      styles = [:original]
      styles += attachment.styles.keys if attachment.styles
      styles.each do |style|
        geo = ::Paperclip::Geometry.from_file(attachment.queued_for_write[style])
        dimension_hash[style.to_s] = [ geo.width.to_i, geo.height.to_i ]
      end
      self.send "#{name}_dimensions=", dimension_hash
    end
  end

  module Glue
    class << self
      def included_with_dimension(klass)
        included_without_dimension(klass)
        klass.send :include, Paperclip::Dimension
      end

      alias :included_without_dimension :included
      alias :included :included_with_dimension
    end
  end

  module Schema
    COLUMNS[:dimensions] = :string
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
paperclip-dimension-0.3.1 lib/paperclip-dimension.rb