2010-09-17 139 views
0

我一直在使用Paperclip爲媒體存儲構建的項目中打破DRY原則。我已經添加了資產某些型號,如AlbumPhotoFile,AlbumSoundFile等,使用下面的代碼:Rails回形針'類方法'和驗證重構?

# Asset is a regular < ActiveRecord::Base class 
class AlbumPhotoFile < Asset 
    has_attached_file :pic, :url => "foo", :path => "bar" 
    validates_attachment_presence :pic, :message => "can't be blank" 
    validates_attachment_content_type :pic, :content_type => ["foo", "bar"] 
end 

縮放到一些更多的要求,我只好照片附加到其他車型,說CityPhotoFile。我想保持驗證和has_attached_file fu與其他PhotoFile類型模型相同。我剛剛將PhotoFile模型的代碼複製粘貼到另一個,是否有更好的方法呢?

沒有任何Paperclip相關的錯誤,存儲和顯示工作正常,我只是想知道,如果這種類型的操作可以放在模塊或類似的東西,爲DRY的緣故。

只是反彈代碼真的越來越醜了。如果我沒有在這個空間裏明確我的意圖,我可以提供更多細節:-)。

預先感謝您!

回答

2

這裏是爲我工作的基礎上,Mr.Matt的解決方案:

# in lib/paperclip_template_audio.rb, for instance 
module PaperclipTemplateAudio 

    # Stuff directives into including module 
    def self.included(recipient) 
    recipient.class_eval do 
     has_attached_file :pic, :url => "foo", :path => "bar" 
     validates_attachment_presence :pic, :message => "can't be blank" 
     validates_attachment_content_type :pic, :content_type => ["foo", "bar"] 
    end 
    end 

end # Module 

在我的模型:

class AlbumPhotoFile < ActiveRecord::Base 
    include PaperclipTemplateAudio 
end 
1

呀,你可以列如下移動代碼到一個模塊中,然後將其包含在你的類:

# in lib/default_paperclip 
module DefaultPaperclip 
    has_attached_file :pic, :url => "foo", :path => "bar" 
    validates_attachment_presence :pic, :message => "can't be blank" 
    validates_attachment_content_type :pic, :content_type => ["foo", "bar"] 
end 


# your active record 
class AlbumPhotoFile < ActiveRecord::Base 
    include DefaultPaperclip 
end 

認爲,應該工作。雖然沒有測試過!

+0

我會嘗試一下,當我回去工作,謝謝你輸入! – Dr1Ku 2010-09-18 11:51:54

+0

還需要包含更多模塊內容,下面列出了工作解決方案。謝謝您的意見 ! – Dr1Ku 2010-09-20 10:37:05