Module: JSONAPI::ActiveStorage::Serialization

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

Class Method Summary collapse

Class Method Details

.serialize_blob_identifier(blob) ⇒ Object



27
28
29
# File 'lib/json_api/active_storage/serialization.rb', line 27

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
19
20
21
22
23
24
25
# 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)

  if attachment.respond_to?(:attached?) && attachment.attached?
    # has_many_attached returns an array-like object
    if attachment.is_a?(::ActiveStorage::Attached::Many)
      attachment.blobs.map { |blob| serialize_blob_identifier(blob) }
    else
      # has_one_attached
      serialize_blob_identifier(attachment.blob)
    end
  elsif attachment.respond_to?(:attached?) && !attachment.attached?
    # Not attached - return nil for has_one, empty array for has_many
    attachment.is_a?(::ActiveStorage::Attached::Many) ? [] : nil
  end
end