Rails 4 - 回形针重构 has_attached_file

Rails 4 - Paperclip refactor out has_attached_file

我在 3 个不同的模型中进行了以下验证。我该如何重构它。

has_attached_file :image,
                    styles: {
                      large: '700x400>',
                      medium: '400x400#',
                      thumb: '100x100#'
                    },
                    default_url: '/images/missing.png'

validates_attachment_content_type :image,
                                    content_type: /\Aimage\/.*\z/

您可以将其移动到 concern。创建关注点最难的部分是命名它。随意更改名称,但我将此问题称为 ImageAttachable。也许这是一个愚蠢的名字,但这是我在短时间内能做的最好的事情。要对此进行编码,请添加以下文件:

app/models/concerns/image_attachable.rb

module ImageAttachable
  extend ActiveSupport::Concern

  included do
    has_attached_file :image,
                  styles: {
                    large: '700x400>',
                    medium: '400x400#',
                    thumb: '100x100#'
                  },
                  default_url: '/images/missing.png'

    validates_attachment_content_type :image,
                                  content_type: /\Aimage\/.*\z/
  end

end

然后您将从您的模型中删除上述所有代码并将其替换为:

include ImageAttachable

DHH 已就该主题撰写 an excellent article