resource.rb
上传用户:netsea168
上传日期:2022-07-22
资源大小:4652k
文件大小:2k
源码类别:

Ajax

开发平台:

Others

  1. require 'tempfile'
  2. require 'mini_magick'
  3. class Resource < ActiveRecord::Base
  4.   validates_uniqueness_of :filename
  5.   after_destroy :delete_filename_on_disk
  6.   before_validation_on_create :uniq_filename_on_disk
  7.   belongs_to :article
  8.   
  9.   def fullpath(file = nil)
  10.     "#{RAILS_ROOT}/public/files/#{file.nil? ? filename : file}"
  11.   end
  12.   def write_to_disk(up)
  13.     begin
  14.       # create the public/files dir if it doesn't exist
  15.       FileUtils.mkdir(fullpath('')) unless File.directory?(fullpath(''))
  16.       if up.kind_of?(Tempfile) and !up.local_path.nil? and File.exist?(up.local_path)
  17.         File.chmod(0600, up.local_path)
  18.         FileUtils.copy(up.local_path, fullpath)
  19.       else
  20.         bytes = up
  21.         if up.kind_of?(StringIO)
  22.           up.rewind
  23.           bytes = up.read
  24.         end
  25.         File.open(fullpath, "wb") { |f| f.write(bytes) }
  26.       end
  27.       File.chmod(0644, fullpath)
  28.       self.size = File.stat(fullpath).size rescue 0
  29.       update
  30.       self
  31.     rescue
  32.       raise
  33.     end
  34.   end
  35.   def create_thumbnail
  36.     return unless self.mime =~ /image/ or File.exists?(fullpath("thumb_#{self.filename}"))
  37.     return unless File.exists?(fullpath("#{self.filename}"))
  38.     begin
  39.       img_orig = MiniMagick::Image.from_file(fullpath(self.filename))
  40.       img_orig = img_orig.resize('125x125')
  41.       img_orig.write(fullpath("thumb_#{self.filename}"))
  42.     rescue
  43.       nil
  44.     end
  45.   end
  46.   protected
  47.   def uniq_filename_on_disk
  48.     i = 0
  49.     raise if filename.empty?
  50.     tmpfile = File.basename(filename.gsub(/\/, '/')).gsub(/[^w.-]/,'_')
  51.     filename = tmpfile
  52.     while File.exist?(fullpath(tmpfile))
  53.       i += 1
  54.       tmpfile = filename.sub(/^(.*?)(.[^.]+)?$/, '1'+"#{i}"+'2')
  55.     end
  56.     self.filename = tmpfile
  57.   end
  58.   def delete_filename_on_disk
  59.     File.unlink(fullpath(filename)) if File.exist?(fullpath(filename))
  60.   end
  61. end