Module: JSONAPI::ActiveStorage::Serialization
- Defined in:
- lib/json_api/active_storage/serialization.rb
Class Method Summary collapse
-
.blobs_for(attachment_name, record) ⇒ Object
Blobs for an attachment.
- .many_blobs(attachment, association) ⇒ Object
- .one_blob(attachment, association) ⇒ Object
- .serialize_blob_identifier(blob) ⇒ Object
- .serialize_relationship(attachment_name, record) ⇒ Object
Class Method Details
.blobs_for(attachment_name, record) ⇒ Object
Blobs for an attachment. Reads through the ActiveStorage associations when the include preloader loaded them (zero queries); otherwise falls back to the probing reader (attached? + blobs, one query each).
23 24 25 26 27 28 29 30 31 32 |
# File 'lib/json_api/active_storage/serialization.rb', line 23 def blobs_for(, record) = record.public_send() return [] unless .respond_to?(:attached?) if .is_a?(::ActiveStorage::Attached::Many) many_blobs(, record.association(:"#{}_attachments")) else one_blob(, record.association(:"#{}_attachment")) end end |
.many_blobs(attachment, association) ⇒ Object
34 35 36 37 38 |
# File 'lib/json_api/active_storage/serialization.rb', line 34 def many_blobs(, association) return association.target.filter_map(&:blob) if association.loaded? .attached? ? .blobs.to_a : [] end |
.one_blob(attachment, association) ⇒ Object
40 41 42 43 44 |
# File 'lib/json_api/active_storage/serialization.rb', line 40 def one_blob(, association) return [association.target&.blob].compact if association.loaded? .attached? ? [.blob].compact : [] end |
.serialize_blob_identifier(blob) ⇒ Object
46 47 48 |
# File 'lib/json_api/active_storage/serialization.rb', line 46 def serialize_blob_identifier(blob) { type: "active_storage_blobs", id: blob.id.to_s } end |
.serialize_relationship(attachment_name, record) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/json_api/active_storage/serialization.rb', line 8 def serialize_relationship(, record) return nil unless defined?(::ActiveStorage) = record.public_send() return nil unless .respond_to?(:attached?) blobs = blobs_for(, record) return blobs.map { |blob| serialize_blob_identifier(blob) } if .is_a?(::ActiveStorage::Attached::Many) blobs.first ? serialize_blob_identifier(blobs.first) : nil end |