Module: JSONAPI::ActiveStorage::Serialization

Defined in:
lib/json_api/active_storage/serialization.rb

Class Method Summary collapse

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(attachment_name, record)
  attachment = record.public_send(attachment_name)
  return [] unless attachment.respond_to?(:attached?)

  if attachment.is_a?(::ActiveStorage::Attached::Many)
    many_blobs(attachment, record.association(:"#{attachment_name}_attachments"))
  else
    one_blob(attachment, record.association(:"#{attachment_name}_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(attachment, association)
  return association.target.filter_map(&:blob) if association.loaded?

  attachment.attached? ? attachment.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(attachment, association)
  return [association.target&.blob].compact if association.loaded?

  attachment.attached? ? [attachment.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(attachment_name, record)
  return nil unless defined?(::ActiveStorage)

  attachment = record.public_send(attachment_name)
  return nil unless attachment.respond_to?(:attached?)

  blobs = blobs_for(attachment_name, record)
  return blobs.map { |blob| serialize_blob_identifier(blob) } if attachment.is_a?(::ActiveStorage::Attached::Many)

  blobs.first ? serialize_blob_identifier(blobs.first) : nil
end