删除附件时跳过 ActiveStorage 文件清除

Skip ActiveStorage File Purge on Attachment Deletion

如标题中所述,我正在尝试获取它,以便我们可以在用户删除我们系统中的附件后跳过 blob 清除。原因是我们希望保留上传文件(或 blob)的副本,即使有人在我们的系统中删除了它们。由于 ActiveStorage 没有为此进行配置,我一直在尝试猴子修补 ActiveStorage::Blob 中的 #purge 方法但没有成功。

这是我的初始化程序:

# config/initializers/active_storage.rb
module CoreExtensions
  module ActiveStorage
    module Blob
      def purge
        raise "here"
      end
    end
  end
end

ActiveSupport::Reloader.to_prepare do
  ActiveStorage::Blob.include CoreExtensions::ActiveStorage::Blob
end

这似乎什么也没做,我的 raise 在删除文件时从未受到影响。

我也试过:

ActiveStorage::Blob.include CoreExtensions::ActiveStorage::Blob

没有 ActiveSupport::Reloader.to_prepare 块,但在启动应用程序时一直出现此错误:"undefined method `has_one_attached'"

有什么办法可以成功地给猴子打补丁吗?跳过 blob 清除的替代想法也很受欢迎。

你可以猴子补丁ActiveStorage::Attachment

将您的初始化代码更改为:

module MonkeyPatch
  def purge
    raise 'your patch here'
  end

  def purge_later
    raise 'and here'
  end
end

ActiveStorage::Attachment.prepend MonkeyPatch

默认情况下它们是:

def purge
  delete
  blob&.purge
end

def purge_later
  delete
  blob&.purge_later
end

我最终发现这有效:

# config/initializers/active_storage.rb
Rails.application.config.after_initialize do
  ActiveStorage::Blob.class_eval do
    def purge
      # skip purge
    end
  end
end