【问题标题】:Rails Paperclip 'class methods' and validations refactor?Rails Paperclip“类方法”和验证重构?
【发布时间】:2010-09-17 08:47:15
【问题描述】:

在一个使用 Paperclip 构建的媒体存储项目中,我已经稍微打破了 DRY 原则。我已使用以下代码将资产添加到某些模型,例如 AlbumPhotoFile、AlbumSoundFile 等:

# 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 模型复制粘贴到另一个模型中,有没有更好的方法?

没有任何与回形针相关的错误,存储和显示工作正常,我只是想知道这种类型的操作是否可以放在模块或类似的东西中,为了 DRY。

只是弹跳代码真的越来越难看。如果我没有在这个领域明确表达我的意图,我可以提供更多细节:-)。

提前谢谢你!

【问题讨论】:

    标签: ruby-on-rails activerecord refactoring paperclip


    【解决方案1】:

    根据 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
    

    【讨论】:

      【解决方案2】:

      是的,您可以将该代码移出到一个模块中,然后将其包含在您的类中,如下所示:

      # 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
      

      认为这应该可行。虽然没有测试!

      【讨论】:

      • 我回去工作后再试试,谢谢你的意见!
      • 还必须包含更多模块内容,我在下面包含了工作解决方案。感谢您的意见!
      猜你喜欢
      • 2023-03-16
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多