Class: ActiveStorage::Blob
- Inherits:
-
Record
- Object
- ActiveRecord::Base
- Record
- ActiveStorage::Blob
- Includes:
- Analyzable, Identifiable, Representable, Servable
- Defined in:
- activestorage/app/models/active_storage/blob.rb
Overview
Active Storage Blob
A blob is a record that contains the metadata about a file and a key for where that file resides on the service. Blobs can be created in two ways:
-
Ahead of the file being uploaded server-side to the service, via
create_and_upload!. A rewindableiowith the file contents must be available at the server for this operation. -
Ahead of the file being directly uploaded client-side to the service, via
create_before_direct_upload!.
The first option doesn’t require any client-side JavaScript integration, and can be used by any other back-end service that deals with files. The second option is faster, since you’re not using your own server as a staging point for uploads, and can work with deployments like Heroku that do not provide large amounts of disk space.
Blobs are intended to be immutable in as-so-far as their reference to a specific file goes. You’re allowed to update a blob’s metadata on a subsequent pass, but you should not update the key or change the uploaded file. If you need to create a derivative or otherwise change the blob, simply create a new blob and purge the old one.
Defined Under Namespace
Modules: Analyzable, Identifiable, Representable, Servable
Constant Summary collapse
- MINIMUM_TOKEN_LENGTH =
28
Constants included from ActiveRecord::ConnectionHandling
ActiveRecord::ConnectionHandling::DEFAULT_ENV, ActiveRecord::ConnectionHandling::RAILS_ENV
Constants included from ActiveRecord::Querying
ActiveRecord::Querying::QUERYING_METHODS
Constants included from ActiveRecord::Transactions
ActiveRecord::Transactions::ACTIONS
Constants included from ActiveModel::SecurePassword
ActiveModel::SecurePassword::DEFAULT_RESET_TOKEN_EXPIRES_IN
Constants included from ActiveRecord::Callbacks
ActiveRecord::Callbacks::CALLBACKS
Constants included from ActiveRecord::AttributeMethods
ActiveRecord::AttributeMethods::RESTRICTED_CLASS_METHODS
Constants included from ActiveModel::AttributeMethods
ActiveModel::AttributeMethods::CALL_COMPILABLE_REGEXP, ActiveModel::AttributeMethods::NAME_COMPILABLE_REGEXP
Instance Attribute Summary collapse
-
#local_io ⇒ Object
Temporary reference to a local io during the upload flow.
Attributes included from ActiveRecord::ConnectionHandling
#connection_specification_name
Attributes included from ActiveRecord::Delegation::DelegateCache
Attributes included from ActiveRecord::Transactions
#_last_transaction_return_status, #_new_record_before_last_commit
Attributes included from ActiveRecord::Core
Class Method Summary collapse
-
.build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) ⇒ Object
:nodoc:.
-
.combine_signed_id_purposes(purpose) ⇒ Object
Customize signed ID purposes for backwards compatibility.
-
.compose(blobs, key: nil, filename:, content_type: nil, metadata: nil) ⇒ Object
Concatenate multiple blobs into a single “composed” blob.
-
.create_after_unfurling!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) ⇒ Object
:nodoc:.
-
.create_and_upload!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) ⇒ Object
Creates a new blob instance and then uploads the contents of the given
ioto the service. -
.create_before_direct_upload!(key: nil, filename:, byte_size:, checksum:, content_type: nil, metadata: nil, service_name: nil, record: nil) ⇒ Object
Returns a saved blob without uploading a file to the service.
-
.find_signed(id, record: nil, purpose: :blob_id) ⇒ Object
You can use the signed ID of a blob to refer to it on the client side without fear of tampering.
-
.find_signed!(id, record: nil, purpose: :blob_id) ⇒ Object
Works like
find_signed, but will raise anActiveSupport::MessageVerifier::InvalidSignatureexception if thesigned_idhas either expired, has a purpose mismatch, or has been tampered with. -
.generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) ⇒ Object
To prevent problems with case-insensitive filesystems, especially in combination with databases which treat indices as case-sensitive, all blob keys generated are going to only contain the base-36 character alphabet and will therefore be lowercase.
-
.scope_for_strict_loading ⇒ Object
:nodoc:.
-
.signed_id_verifier ⇒ Object
Customize the default signed ID verifier for backwards compatibility.
Instance Method Summary collapse
-
#attachments ⇒ Object
:method:.
-
#audio? ⇒ Boolean
Returns true if the content_type of this blob is in the audio range, like audio/mpeg.
-
#compose(keys) ⇒ Object
:nodoc:.
- #custom_metadata ⇒ Object
- #custom_metadata=(metadata) ⇒ Object
-
#delete ⇒ Object
Deletes the files on the service associated with the blob.
-
#download(&block) ⇒ Object
Downloads the file associated with this blob.
-
#download_chunk(range) ⇒ Object
Downloads a part of the file associated with this blob.
-
#filename ⇒ Object
Returns an ActiveStorage::Filename instance of the filename that can be queried for basename, extension, and a sanitized version of the filename that’s safe to use in URLs.
-
#image? ⇒ Boolean
Returns true if the content_type of this blob is in the image range, like image/png.
-
#key ⇒ Object
Returns the key pointing to the file on the service that’s associated with this blob.
-
#mirror_later ⇒ Object
:nodoc:.
-
#open(tmpdir: nil, &block) ⇒ Object
Downloads the blob to a temporary file on disk.
-
#purge ⇒ Object
Destroys the blob record and then deletes the file on the service.
-
#purge_later ⇒ Object
Enqueues an ActiveStorage::PurgeJob to call #purge.
-
#service ⇒ Object
Returns an instance of service, which can be configured globally or per attachment.
-
#service_headers_for_direct_upload ⇒ Object
Returns a Hash of headers for
service_url_for_direct_uploadrequests. -
#service_url_for_direct_upload(expires_in: ActiveStorage.service_urls_expire_in) ⇒ Object
Returns a URL that can be used to directly upload a file for this blob on the service.
-
#signed_id(purpose: :blob_id, expires_in: nil, expires_at: nil) ⇒ Object
Returns a signed ID for this blob that’s suitable for reference on the client-side without fear of tampering.
-
#text? ⇒ Boolean
Returns true if the content_type of this blob is in the text range, like text/plain.
-
#unattached ⇒ Object
:singleton-method:.
-
#unfurl(io, identify: true) ⇒ Object
:nodoc:.
-
#upload(io, identify: true) ⇒ Object
Uploads the
ioto the service on thekeyfor this blob. -
#upload_without_unfurling(io) ⇒ Object
:nodoc:.
-
#url(expires_in: ActiveStorage.service_urls_expire_in, disposition: :inline, filename: nil, **options) ⇒ Object
Returns the URL of the blob on the service.
-
#video? ⇒ Boolean
Returns true if the content_type of this blob is in the video range, like video/mp4.
Methods included from Servable
#content_type_for_serving, #forced_disposition_for_serving
Methods included from Representable
#preview, #previewable?, #representable?, #representation, #variable?, #variant
Methods included from ActiveSupport::Concern
#append_features, #class_methods, extended, #included, #prepend_features, #prepended
Methods included from Identifiable
#identified?, #identify, #identify_without_saving
Methods included from Analyzable
#analyze, #analyze_later, #analyze_without_saving, #analyzed?
Methods included from ActiveSupport::Benchmarkable
Methods included from ActiveSupport::DescendantsTracker
clear, #descendants, descendants, disable_clear!, reject!, subclasses
Methods included from ActiveRecord::ConnectionHandling
#adapter_class, #clear_cache!, #clear_query_caches_for_current_thread, #connected?, #connected_to, #connected_to?, #connected_to_all_shards, #connected_to_many, #connecting_to, #connection, #connection_db_config, #connection_pool, #connects_to, #establish_connection, #lease_connection, #primary_class?, #prohibit_shard_swapping, #release_connection, #remove_connection, #retrieve_connection, #schema_cache, #shard_keys, #shard_swapping_prohibited?, #sharded?, #while_preventing_writes, #with_connection
Methods included from ActiveRecord::QueryCache::ClassMethods
Methods included from ActiveRecord::Querying
#_load_from_sql, #_query_by_sql, #async_count_by_sql, #async_find_by_sql, #count_by_sql, #find_by_sql
Methods included from ActiveRecord::Translation
#i18n_scope, #lookup_ancestors
Methods included from ActiveRecord::DelegatedType
Methods included from ActiveRecord::Explain
#collecting_queries_for_explain, #exec_explain
Methods included from ActiveRecord::Enum
Methods included from ActiveRecord::Delegation::DelegateCache
#generate_relation_method, #inherited, #initialize_relation_delegate_cache, #relation_delegate_class
Methods included from ActiveRecord::Aggregations::ClassMethods
Methods included from ActiveRecord::Marshalling::Methods
#_marshal_dump_7_1, #marshal_load
Methods included from ActiveRecord::Suppressor
Methods included from ActiveRecord::TokenFor
Methods included from ActiveRecord::Serialization
Methods included from ActiveModel::Serializers::JSON
Methods included from ActiveModel::Serialization
Methods included from ActiveRecord::Reflection
add_aggregate_reflection, add_reflection, create
Methods included from ActiveRecord::NoTouching
applied_to?, apply_to, #no_touching?, #touch, #touch_later
Methods included from ActiveRecord::TouchLater
#before_committed!, #touch, #touch_later
Methods included from ActiveRecord::Transactions
#before_committed!, #committed!, #destroy, #rolledback!, #save, #save!, #touch, #transaction, #trigger_transactional_callbacks?, #with_transaction_returning_status
Methods included from ActiveRecord::NestedAttributes
Methods included from ActiveRecord::AutosaveAssociation
#autosaving_belongs_to_for?, #changed_for_autosave?, #destroyed_by_association, #destroyed_by_association=, #mark_for_destruction, #marked_for_destruction?, #reload, #validating_belongs_to_for?
Methods included from ActiveModel::SecurePassword
algorithm_registry, lookup_algorithm, register_algorithm
Methods included from ActiveRecord::Associations
#association, #association_cached?, eager_load!, #initialize_dup
Methods included from ActiveSupport::Autoload
#autoload, #autoload_at, #autoload_under, #eager_autoload, #eager_load!
Methods included from ActiveRecord::Timestamp
Methods included from ActiveRecord::Callbacks
Methods included from ActiveRecord::AttributeMethods
#[], #[]=, #_has_attribute?, #accessed_fields, #attribute_for_inspect, #attribute_names, #attribute_present?, #attributes, dangerous_attribute_methods, #has_attribute?, #respond_to?
Methods included from ActiveModel::AttributeMethods
#attribute_missing, #method_missing, #respond_to?, #respond_to_without_attributes?
Methods included from ActiveRecord::Encryption::EncryptableRecord
#ciphertext_for, #decrypt, #encrypt, #encrypted_attribute?
Methods included from ActiveRecord::Locking::Pessimistic
Methods included from ActiveRecord::Locking::Optimistic
#increment!, #initialize_dup, #locking_enabled?
Methods included from ActiveModel::Attributes::Normalization
Methods included from ActiveRecord::Validations
#custom_validation_context?, #save, #save!, #valid?
Methods included from ActiveRecord::Integration
#cache_key, #cache_key_with_version, #cache_version, #to_param
Methods included from ActiveRecord::Scoping
#initialize_internals_callback, #populate_with_current_scope_attributes
Methods included from ActiveRecord::Inheritance
Methods included from ActiveRecord::ModelSchema
Methods included from ActiveRecord::Persistence
#becomes, #becomes!, #decrement, #decrement!, #destroy, #destroy!, #destroyed?, #increment, #increment!, #new_record?, #persisted?, #previously_new_record?, #previously_persisted?, #reload, #save, #save!, #toggle, #toggle!, #touch, #update, #update!, #update_attribute, #update_attribute!, #update_column, #update_columns
Methods included from ActiveRecord::Core
#<=>, #==, #blank?, #connection_handler, #encode_with, #freeze, #frozen?, #full_inspect, #hash, #init_attributes, #init_with, #init_with_attributes, #initialize, #initialize_dup, #inspect, #present?, #pretty_print, #readonly!, #readonly?, #strict_loading!, #strict_loading?, #strict_loading_all?, #strict_loading_n_plus_one_only?
Methods included from ActiveModel::Access
Methods included from ActiveModel::API
Methods included from ActiveModel::Conversion
#to_key, #to_model, #to_param, #to_partial_path
Methods included from ActiveModel::Validations
#errors, #freeze, #initialize_dup, #invalid?, #read_attribute_for_validation, #valid?, #validate!, #validates_with, #validation_context
Methods included from ActiveModel::AttributeAssignment
#assign_attributes, #attribute_writer_missing
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class ActiveRecord::AttributeMethods
Instance Attribute Details
#local_io ⇒ Object
Temporary reference to a local io during the upload flow. When set, open will use this instead of downloading from the service. This enables analysis and other operations to run on the local file before uploading, avoiding a download round-trip.
29 30 31 |
# File 'activestorage/app/models/active_storage/blob.rb', line 29 def local_io @local_io end |
Class Method Details
.build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) ⇒ Object
:nodoc:
86 87 88 89 90 |
# File 'activestorage/app/models/active_storage/blob.rb', line 86 def build_after_unfurling(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) # :nodoc: new(key: key, filename: filename, content_type: content_type, metadata: , service_name: service_name).tap do |blob| blob.unfurl(io, identify: identify) end end |
.combine_signed_id_purposes(purpose) ⇒ Object
Customize signed ID purposes for backwards compatibility.
126 127 128 |
# File 'activestorage/app/models/active_storage/blob.rb', line 126 def combine_signed_id_purposes(purpose) # :nodoc: purpose.to_s end |
.compose(blobs, key: nil, filename:, content_type: nil, metadata: nil) ⇒ Object
Concatenate multiple blobs into a single “composed” blob.
150 151 152 153 154 155 156 157 158 159 |
# File 'activestorage/app/models/active_storage/blob.rb', line 150 def compose(blobs, key: nil, filename:, content_type: nil, metadata: nil) raise ActiveRecord::RecordNotSaved, "All blobs must be persisted." if blobs.any?(&:new_record?) content_type ||= blobs.pluck(:content_type).compact.first new(key: key, filename: filename, content_type: content_type, metadata: , byte_size: blobs.sum(&:byte_size)).tap do |combined_blob| combined_blob.compose(blobs.pluck(:key)) combined_blob.save! end end |
.create_after_unfurling!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) ⇒ Object
:nodoc:
92 93 94 |
# File 'activestorage/app/models/active_storage/blob.rb', line 92 def create_after_unfurling!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) # :nodoc: build_after_unfurling(key: key, io: io, filename: filename, content_type: content_type, metadata: , service_name: service_name, identify: identify).tap(&:save!) end |
.create_and_upload!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) ⇒ Object
Creates a new blob instance and then uploads the contents of the given io to the service. The blob instance is going to be saved before the upload begins to prevent the upload clobbering another due to key collisions. When providing a content type, pass identify: false to bypass automatic content type inference.
101 102 103 104 105 |
# File 'activestorage/app/models/active_storage/blob.rb', line 101 def create_and_upload!(key: nil, io:, filename:, content_type: nil, metadata: nil, service_name: nil, identify: true, record: nil) create_after_unfurling!(key: key, io: io, filename: filename, content_type: content_type, metadata: , service_name: service_name, identify: identify).tap do |blob| blob.upload_without_unfurling(io) end end |
.create_before_direct_upload!(key: nil, filename:, byte_size:, checksum:, content_type: nil, metadata: nil, service_name: nil, record: nil) ⇒ Object
Returns a saved blob without uploading a file to the service. This blob will point to a key where there is no file yet. It’s intended to be used together with a client-side upload, which will first create the blob in order to produce the signed URL for uploading. This signed URL points to the key generated by the blob. Once the form using the direct upload is submitted, the blob can be associated with the right record using the signed ID.
112 113 114 |
# File 'activestorage/app/models/active_storage/blob.rb', line 112 def create_before_direct_upload!(key: nil, filename:, byte_size:, checksum:, content_type: nil, metadata: nil, service_name: nil, record: nil) create! key: key, filename: filename, byte_size: byte_size, checksum: checksum, content_type: content_type, metadata: , service_name: service_name end |
.find_signed(id, record: nil, purpose: :blob_id) ⇒ Object
You can use the signed ID of a blob to refer to it on the client side without fear of tampering. This is particularly helpful for direct uploads where the client-side needs to refer to the blob that was created ahead of the upload itself on form submission.
The signed ID is also used to create stable URLs for the blob through the BlobsController.
75 76 77 |
# File 'activestorage/app/models/active_storage/blob.rb', line 75 def find_signed(id, record: nil, purpose: :blob_id) super(id, purpose: purpose) end |
.find_signed!(id, record: nil, purpose: :blob_id) ⇒ Object
Works like find_signed, but will raise an ActiveSupport::MessageVerifier::InvalidSignature exception if the signed_id has either expired, has a purpose mismatch, or has been tampered with. It will also raise an ActiveRecord::RecordNotFound exception if the valid signed id can’t find a record.
82 83 84 |
# File 'activestorage/app/models/active_storage/blob.rb', line 82 def find_signed!(id, record: nil, purpose: :blob_id) super(id, purpose: purpose) end |
.generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) ⇒ Object
To prevent problems with case-insensitive filesystems, especially in combination with databases which treat indices as case-sensitive, all blob keys generated are going to only contain the base-36 character alphabet and will therefore be lowercase. To maintain the same or higher amount of entropy as in the base-58 encoding used by has_secure_token the number of bytes used is increased to 28 from the standard 24
121 122 123 |
# File 'activestorage/app/models/active_storage/blob.rb', line 121 def generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) SecureRandom.base36(length) end |
.scope_for_strict_loading ⇒ Object
:nodoc:
138 139 140 141 142 143 144 145 146 147 |
# File 'activestorage/app/models/active_storage/blob.rb', line 138 def scope_for_strict_loading # :nodoc: if strict_loading_by_default? && ActiveStorage.track_variants includes( variant_records: { image_attachment: :blob }, preview_image_attachment: { blob: { variant_records: { image_attachment: :blob } } } ) else all end end |
.signed_id_verifier ⇒ Object
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.
134 135 136 |
# File 'activestorage/app/models/active_storage/blob.rb', line 134 def signed_id_verifier # :nodoc: @signed_id_verifier ||= ActiveStorage.verifier end |
Instance Method Details
#attachments ⇒ Object
:method:
Returns the associated ActiveStorage::Attachment instances.
38 |
# File 'activestorage/app/models/active_storage/blob.rb', line 38 has_many :attachments, autosave: false |
#audio? ⇒ Boolean
Returns true if the content_type of this blob is in the audio range, like audio/mpeg.
202 203 204 |
# File 'activestorage/app/models/active_storage/blob.rb', line 202 def audio? content_type.start_with?("audio") end |
#compose(keys) ⇒ Object
:nodoc:
265 266 267 268 |
# File 'activestorage/app/models/active_storage/blob.rb', line 265 def compose(keys) # :nodoc: self.composed = true service.compose(keys, key, **) end |
#custom_metadata ⇒ Object
188 189 190 |
# File 'activestorage/app/models/active_storage/blob.rb', line 188 def self[:metadata][:custom] || {} end |
#custom_metadata=(metadata) ⇒ Object
192 193 194 |
# File 'activestorage/app/models/active_storage/blob.rb', line 192 def () self[:metadata] = self[:metadata].merge(custom: ) end |
#delete ⇒ Object
Deletes the files on the service associated with the blob. This should only be done if the blob is going to be deleted as well or you will essentially have a dead reference. It’s recommended to use #purge and #purge_later methods in most circumstances.
315 316 317 318 |
# File 'activestorage/app/models/active_storage/blob.rb', line 315 def delete service.delete(key) service.delete_prefixed("variants/#{key}/") if image? end |
#download(&block) ⇒ Object
Downloads the file associated with this blob. If no block is given, the entire file is read into memory and returned. That’ll use a lot of RAM for very large files. If a block is given, then the download is streamed and yielded in chunks.
272 273 274 |
# File 'activestorage/app/models/active_storage/blob.rb', line 272 def download(&block) service.download key, &block end |
#download_chunk(range) ⇒ Object
Downloads a part of the file associated with this blob.
277 278 279 |
# File 'activestorage/app/models/active_storage/blob.rb', line 277 def download_chunk(range) service.download_chunk key, range end |
#filename ⇒ Object
Returns an ActiveStorage::Filename instance of the filename that can be queried for basename, extension, and a sanitized version of the filename that’s safe to use in URLs.
184 185 186 |
# File 'activestorage/app/models/active_storage/blob.rb', line 184 def filename ActiveStorage::Filename.new(self[:filename]) end |
#image? ⇒ Boolean
Returns true if the content_type of this blob is in the image range, like image/png.
197 198 199 |
# File 'activestorage/app/models/active_storage/blob.rb', line 197 def image? content_type.start_with?("image") end |
#key ⇒ Object
Returns the key pointing to the file on the service that’s associated with this blob. The key is the secure-token format from Rails in lower case. So it’ll look like: xtapjjcjiudrlk3tmwyjgpuobabd. This key is not intended to be revealed directly to the user. Always refer to blobs using the signed_id or a verified form of the key.
176 177 178 179 |
# File 'activestorage/app/models/active_storage/blob.rb', line 176 def key # We can't wait until the record is first saved to have a key for it self[:key] ||= self.class.generate_unique_secure_token(length: MINIMUM_TOKEN_LENGTH) end |
#mirror_later ⇒ Object
:nodoc:
308 309 310 |
# File 'activestorage/app/models/active_storage/blob.rb', line 308 def mirror_later # :nodoc: service.mirror_later key, checksum: checksum if service.respond_to?(:mirror_later) end |
#open(tmpdir: nil, &block) ⇒ Object
Downloads the blob to a temporary file on disk. If a block is given, the file is automatically closed and unlinked after the block executed. Otherwise the file is returned and you are responsible for closing and unlinking.
The tempfile’s name is prefixed with ActiveStorage- and the blob’s ID. Its extension matches that of the blob.
By default, the tempfile is created in Dir.tmpdir. Pass tmpdir: to create it in a different directory:
blob.open(tmpdir: "/path/to/tmp") do |file|
# ...
end
Raises ActiveStorage::IntegrityError if the downloaded data does not match the blob’s checksum.
293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'activestorage/app/models/active_storage/blob.rb', line 293 def open(tmpdir: nil, &block) if local_io open_local_io(tmpdir: tmpdir, &block) else service.open( key, checksum: checksum, verify: !composed, name: [ "ActiveStorage-#{id}-", filename.extension_with_delimiter ], tmpdir: tmpdir, &block ) end end |
#purge ⇒ Object
Destroys the blob record and then deletes the file on the service. This is the recommended way to dispose of unwanted blobs. Note, though, that deleting the file off the service will initiate an HTTP connection to the service, which may be slow or prevented, so you should not use this method inside a transaction or in callbacks. Use #purge_later instead.
323 324 325 326 327 |
# File 'activestorage/app/models/active_storage/blob.rb', line 323 def purge destroy delete if previously_persisted? rescue ActiveRecord::InvalidForeignKey end |
#purge_later ⇒ Object
Enqueues an ActiveStorage::PurgeJob to call #purge. This is the recommended way to purge blobs from a transaction, an Active Record callback, or in any other real-time scenario.
331 332 333 |
# File 'activestorage/app/models/active_storage/blob.rb', line 331 def purge_later ActiveStorage::PurgeJob.perform_later(self) end |
#service ⇒ Object
Returns an instance of service, which can be configured globally or per attachment
336 337 338 |
# File 'activestorage/app/models/active_storage/blob.rb', line 336 def service services.fetch(service_name) if service_name end |
#service_headers_for_direct_upload ⇒ Object
Returns a Hash of headers for service_url_for_direct_upload requests.
232 233 234 |
# File 'activestorage/app/models/active_storage/blob.rb', line 232 def service_headers_for_direct_upload service.headers_for_direct_upload key, filename: filename, content_type: content_type, content_length: byte_size, checksum: checksum, custom_metadata: end |
#service_url_for_direct_upload(expires_in: ActiveStorage.service_urls_expire_in) ⇒ Object
Returns a URL that can be used to directly upload a file for this blob on the service. This URL is intended to be short-lived for security and only generated on-demand by the client-side JavaScript responsible for doing the uploading.
227 228 229 |
# File 'activestorage/app/models/active_storage/blob.rb', line 227 def service_url_for_direct_upload(expires_in: ActiveStorage.service_urls_expire_in) service.url_for_direct_upload key, expires_in: expires_in, content_type: content_type, content_length: byte_size, checksum: checksum, custom_metadata: end |
#signed_id(purpose: :blob_id, expires_in: nil, expires_at: nil) ⇒ Object
Returns a signed ID for this blob that’s suitable for reference on the client-side without fear of tampering.
168 169 170 |
# File 'activestorage/app/models/active_storage/blob.rb', line 168 def signed_id(purpose: :blob_id, expires_in: nil, expires_at: nil) super end |
#text? ⇒ Boolean
Returns true if the content_type of this blob is in the text range, like text/plain.
212 213 214 |
# File 'activestorage/app/models/active_storage/blob.rb', line 212 def text? content_type.start_with?("text") end |
#unattached ⇒ Object
:singleton-method:
Returns the blobs that aren’t attached to any record.
44 |
# File 'activestorage/app/models/active_storage/blob.rb', line 44 scope :unattached, -> { where.missing(:attachments) } |
#unfurl(io, identify: true) ⇒ Object
:nodoc:
254 255 256 257 258 259 |
# File 'activestorage/app/models/active_storage/blob.rb', line 254 def unfurl(io, identify: true) # :nodoc: self.checksum = service&.compute_checksum(io) self.content_type = extract_content_type(io) if content_type.nil? || identify self.byte_size = io.size self.identified = true end |
#upload(io, identify: true) ⇒ Object
Uploads the io to the service on the key for this blob. Blobs are intended to be immutable, so you shouldn’t be using this method after a file has already been uploaded to fit with a blob. If you want to create a derivative blob, you should instead simply create a new blob based on the old one.
Prior to uploading, we compute the checksum, which is sent to the service for transit integrity validation. If the checksum does not match what the service receives, an exception will be raised. We also measure the size of the io and store that in byte_size on the blob record. The content type is automatically extracted from the io unless you specify a content_type and pass identify as false.
Normally, you do not have to call this method directly at all. Use the create_and_upload! class method instead. If you do use this method directly, make sure you are using it on a persisted Blob as otherwise another blob’s data might get overwritten on the service.
249 250 251 252 |
# File 'activestorage/app/models/active_storage/blob.rb', line 249 def upload(io, identify: true) unfurl io, identify: identify upload_without_unfurling io end |
#upload_without_unfurling(io) ⇒ Object
:nodoc:
261 262 263 |
# File 'activestorage/app/models/active_storage/blob.rb', line 261 def upload_without_unfurling(io) # :nodoc: service.upload key, io, checksum: checksum, ** end |
#url(expires_in: ActiveStorage.service_urls_expire_in, disposition: :inline, filename: nil, **options) ⇒ Object
Returns the URL of the blob on the service. This returns a permanent URL for public files, and returns a short-lived URL for private files. Private files are signed, and not for public use. Instead, the URL should only be exposed as a redirect from a stable, possibly authenticated URL. Hiding the URL behind a redirect also allows you to change services without updating all URLs.
220 221 222 223 |
# File 'activestorage/app/models/active_storage/blob.rb', line 220 def url(expires_in: ActiveStorage.service_urls_expire_in, disposition: :inline, filename: nil, **) service.url key, expires_in: expires_in, filename: ActiveStorage::Filename.wrap(filename || self.filename), content_type: content_type_for_serving, disposition: forced_disposition_for_serving || disposition, ** end |
#video? ⇒ Boolean
Returns true if the content_type of this blob is in the video range, like video/mp4.
207 208 209 |
# File 'activestorage/app/models/active_storage/blob.rb', line 207 def video? content_type.start_with?("video") end |