image.rb 2.03 KB
require "mini_magick"

module Kanjai
  class Image < ActiveRecord::Base
    acts_as_taggable
    
    belongs_to :object, polymorphic: true, optional: true

    IMAGE_MIME_TYPE = ['image/bmp', 'image/gif', 'image/jpeg', 'image/pipeg', 'image/svg+xml', 'image/png']
    PDF_MIME_TYPE = ['application/pdf']

#    has_attached_file :image,
#                      :styles => {:mini => '200x200>'},
#                      :path => ":object_type/:object_id/images/:id/:style/:basename.:extension",
#                      :s3_permissions => :public_read,
#                      :url => ':s3_domain_url'


    default_scope { order('created_at') }

    after_destroy :clear_storage

    def self.get_image_file_path
      "images/"
    end

    def self.get_thumb_image_file_path
      "thumbnailImage/"
    end  

    def resize!
      if image_link.present? && file_type.present? && Kanjai::Image::IMAGE_MIME_TYPE.include?(file_type)
        begin
          obj = S3_BUCKET.object(image_link.split('/')[3..-1].join('/'))
          img = MiniMagick::Image.open(obj.public_url)
          img.resize "400x400"
          img.format "png"

          thumb_image_link = image_link.split('/')[3..-1].join('/').gsub(Kanjai::Image.get_image_file_path, Kanjai::Image.get_thumb_image_file_path)
          obj = S3_BUCKET.put_object({
                                 acl: 'public-read',
                                 body: img.to_blob,
                                 content_type: file_type,
                                 key: thumb_image_link
                               })
          update_column(:thumb_image_link, obj.public_url)
        rescue

        end
      end
    end  

    def preview_link
      thumb_image_link || image_link
    end

    private

    def clear_storage
      if image_link.present?
        obj = S3_BUCKET.object(image_link.split('/')[3..-1].join('/'))
        obj.delete
      end
      if thumb_image_link.present?
        obj = S3_BUCKET.object(thumb_image_link.split('/')[3..-1].join('/'))
        obj.delete
      end      
    end

  end
end