I want to patch Rails 6.0 to include part of this PR: https://github.com/rails/rails/commit/4dba136c83cc808282625c0d5b195ce5e0bbaa68
I'm only using direct uploads so I'm only patching create_before_direct_upload!
at the moment. Here is what I have tried:
- In
initializers/active_storage.rb
module BlobOverride
class << self
def create_before_direct_upload!(key: nil, filename:, byte_size:, checksum:, content_type: nil, metadata: nil)
puts "In Blob Override Patch"
byebug
create! key: key, filename: filename, byte_size: byte_size, checksum: checksum, content_type: content_type, metadata: metadata
end
end
end
ActiveStorage::Blob.prepend(BlobOverride)
This returns the undefined method
has_one_attached'` error, which I tracked down to a github issue here: https://github.com/rails/rails/issues/38876 Which basically says you can't use load the model from the initializer.
2. I then tried loading the module this way:
ActiveSupport.on_load(:active_storage_blob) do
ActiveStorage::Blob.prepend(BlobOverride)
end
And I didn't get an error but my patch wasn't hit.
3. I tried this:
Rails.application.config.to_prepare do
require 'active_storage/blob'
ActiveStorage::Blob.class_eval do
def create_before_direct_upload!(key: nil, filename:, byte_size:, checksum:, content_type: nil, metadata: nil)
puts "in create before direct upload patch"
byebug
create! key: key, filename: filename, byte_size: byte_size, checksum: checksum, content_type: content_type, metadata: metadata
end
end
end
No error, patched method wasn't hit.
TLDR
How do I patch the blob
model on active storage to support a custom key? The standard monkey patching isn't working for some reason.
This applies for Rails 6.1:
ActiveRecord now has a thing called
has_secure_token
, which ActiveStorage is using on Blob. Thishas_secure_token
is setting abefore_create
with the following code:This in turn sets
self[:key]
to be a secure_tokenWhen it's being called like this, the
self[:key]
method only sets it if it doesn't existI fixed this by doing the following in
config/application.rb