MicahBrown
MicahBrown

Reputation: 86

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.

Upvotes: 2

Views: 827

Answers (2)

MicahBrown
MicahBrown

Reputation: 86

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

Upvotes: 2

mechnicov
mechnicov

Reputation: 15248

You can monkey patch ActiveStorage::Attachment

Change your initializer code to this:

module MonkeyPatch
  def purge
    raise 'your patch here'
  end

  def purge_later
    raise 'and here'
  end
end

ActiveStorage::Attachment.prepend MonkeyPatch

By default they are:

def purge
  delete
  blob&.purge
end

def purge_later
  delete
  blob&.purge_later
end

Upvotes: 1

Related Questions