paperclip插件

gem "paperclip", '3.0.0'
gem "upyun-paperclip"
gem 'mime-types', :require => 'mime/types'

 

rails generate model pic

rails generate paperclip pic avatar

 

class EventPic < ActiveRecord::Base
  # attr_accessible :title, :body
  has_attached_file :avatar,
    {
    :storage => :upyun,
    # Please set these four options found in your upyun account.
    :upyun_bucketname => 'public-hall',
    :upyun_username => 'zoro',
    :upyun_password => 'roronoa',
    :upyun_domain => 'public-hall.b0.upaiyun.com'
  }
  before_create :randomize_file_name

  def self.save_event_image(file)
    event_pic = EventPic.new
    event_pic.avatar = file
    event_pic.save
    event_pic
  end

  #type = [  "small"   #=> 180 x 240 ]
  #type = [  "medium"   #=> 200 x 150 ]
  #type = [  "big"   #=> 960 x auto ] 
  def get_image(type = nil)
    if type
      return "http://"+self.avatar.url.gsub(/\?\d*/, "")+"!#{type}"
    else
      return "http://"+self.avatar.url
    end
  end


  private
  def randomize_file_name
    #archives 就是你在 has_attached_file :archives 使用的名字
    extension = File.extname(avatar_file_name).downcase
    #你可以改成你想要的文件名,把下面这个方法的第二个参数随便改了就可以了。
    self.avatar.instance_write(:file_name, "p_i_#{Time.now.strftime("%Y%m%d%H%M%S")}#{extension}")
  end
end

posted @ 2013-03-21 17:33  小狸的窝  阅读(302)  评论(0编辑  收藏  举报