Override ActiveStorage.signed_id_verifier instead of assigning

Guard against the case where ActiveStorage.verifier isn't yet initialized at load time.

Yes, you're not supposed to load AR models in initializers, but it's easy to do accidentally as long as we don't prevent it. We should be resilient against it wherever practical.
This commit is contained in:
George Claghorn 2020-09-02 08:41:15 -04:00
parent f08ae57955
commit 9055156668

@ -35,7 +35,6 @@ class ActiveStorage::Blob < ActiveRecord::Base
include ActiveStorage::Blob::Representable
self.table_name = "active_storage_blobs"
self.signed_id_verifier = ActiveStorage.verifier
MINIMUM_TOKEN_LENGTH = 28
@ -130,9 +129,17 @@ def generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH)
end
# Customize signed ID purposes for backwards compatibility.
def combine_signed_id_purposes(purpose)
def combine_signed_id_purposes(purpose) #:nodoc:
purpose.to_s
end
# Customize the default signed ID verifier for backwards compatibility.
#
# We override the reader (.signed_id_verifier) instead of just calling the writer (.signed_id_verifier=)
# to guard against the case where ActiveStorage.verifier isn't yet initialized at load time.
def signed_id_verifier #:nodoc:
@signed_id_verifier ||= ActiveStorage.verifier
end
end
# Returns a signed ID for this blob that's suitable for reference on the client-side without fear of tampering.