Search code examples
ruby-on-railsrubyrails-activestorage

Skip ActiveStorage File Purge on Attachment Deletion


As stated in the title, I'm trying to get it so that we can skip the blob purging once a user deletes an attachment in our system. The reason is that we want to keep copies of the uploaded files (or blobs), even if someone removes them in our system. Since ActiveStorage has no configuration for this, I've been trying to monkey patch the #purge method in ActiveStorage::Blob without success.

Here's my initializer:

# 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

That seems to do nothing and my raise never gets hit when I delete a file.

I also tried:

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

without the ActiveSupport::Reloader.to_prepare block, but kept getting this error when starting the application: "undefined method `has_one_attached'"

Any ideas how I can successfully monkey patch this? Alternative ideas for skipping the blob purge are also appreciated.


Solution

  • I ended finding out that this worked:

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