2013-07-11 23 views
3

我有一個使用回形針處理圖像的模型。當圖片上傳時,會進行一些JavaScript裁剪的預覽,然後根據所選的裁剪製作縮略圖和預覽尺寸。將回形針附件的所有樣式複製到新對象(S3)

  • 原始圖像
  • 預覽(從用戶選擇的裁剪)
  • 拇指(從用戶選擇的裁剪)

在模型中的代碼:在S3總給我們3個圖像附件是:

has_attached_file :picture, ASSET_INFO.merge(
    :whiny => false, 
    :styles  => { :thumb => '200>x200#', :preview => '400x300>' }, 
    :processors => [:jcropper], 
    :preserve_files => true 
) 

我們有一些功能,允許用戶創建對象的副本的自己的目的,我們想複製圖像。我認爲只是做一個簡單的

new_my_model.picture = original_my_model.picture if original_my_model.picture_file_name #no file name means no picture 

會得到的工作完成,它確實,但只有一種。

它正在複製圖片,然後根據模型中設置的內容重新處理預覽和縮略圖。

我想要做的是將所有3個現有圖像(原始圖像,縮略圖和預覽圖像)複製到新的對象,因爲它們是原始圖像,然後將它們保存在S3的適當位置,跳過調整大小/裁剪。

任何人都可以指向正確的方向嗎?我在網上搜索,似乎無法找到任何東西,我嘗試的一切似乎都不起作用。對原始圖片做一個.dup會導致一個異常,所以這個想法就沒有了。

+0

同樣的問題,我還增加了對最佳答案的評論中http://stackoverflow.com/questions/14224080/ruby-copy-a-paperclip-attachment-from-one -model-to- –

回答

2

手動裁剪打破了Paperclip的自動裁剪/調整大小的方案。沒關係,直到你想將一個附件從一個模型複製到另一個模型。您有兩種選擇: 保存數據庫中每種樣式的裁剪參數,並調用「重新處理!」 。複製(based on the this question)

我無意保存在數據庫裁剪的數據,這是完全沒用的,我決定一味複製圖像嘍,直接調用S3不是最優的,但作品:。

module Customizable 

    def duplicate copy_args 
    new_model = self.dup 
    copy_args.each {|key, val| new_model[key] = val} 
    new_model.save 

    s3 = AWS::S3.new(self.image.s3_credentials) 
    bucket = s3.buckets[self.image.s3_credentials[:bucket]] 

    styles = self.image.styles.keys.insert(0, :original) 

    begin 
     styles.each do |style| 
     current_url = self.image.path(style) 
     current_object = bucket.objects[current_url] 
     if current_object.exists? 
      # actually asking S3 if object exists 
      new_url = new_model.image.path(style) 
      new_object = bucket.objects.create(new_url) 
      # this is where the copying takes place: 
      new_object.copy_from(current_object) 
      new_object.acl = current_object.acl 
     end 
     end 
    rescue Exception => err 
     return err 
    end 

    return true 
    end 

end 

在我的模型:

class Product < ActiveRecord::Base 

    # ... 
    has_attached_file :image, ... 
    # ... 
    include Customizable 

    def customize product_id 
    return self.duplicate({:in_sale => false}) #resetting some values to the duplicated model 
    end 

    # ... 
end 
這裏
+0

不確定你的「目標」是什麼t_name'方法,當你可以使用Paperclip的'path(:style)'方法來生成相同的字符串。 – Sbbs

+0

S B - 好點,回答編輯!我不知道這種方法。 –

+0

是不是new_url只是給你一樣的current_url,因爲new_model.image指向與你self.image相同的東西,當你重複它? – krx