Module: JSONAPI::ActiveStorage::Detection

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

Class Method Summary collapse

Class Method Details

.attachment?(association_name, model_class) ⇒ Boolean

Returns:

  • (Boolean)


8
9
10
11
12
13
# File 'lib/json_api/active_storage/detection.rb', line 8

def attachment?(association_name, model_class)
  return false unless defined?(::ActiveStorage)

  model_class.respond_to?(:reflect_on_attachment) &&
    model_class.reflect_on_attachment(association_name.to_sym).present?
end

.blob_type?(type) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
19
# File 'lib/json_api/active_storage/detection.rb', line 15

def blob_type?(type)
  return false unless defined?(::ActiveStorage)

  type.to_s == "active_storage_blobs"
end

.filter_from_includes(includes_hash, current_model_class) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/json_api/active_storage/detection.rb', line 21

def filter_from_includes(includes_hash, current_model_class)
  return {} unless defined?(::ActiveStorage)

  filtered = {}
  includes_hash.each do |key, value|
    # Skip ActiveStorage attachments - they'll be loaded on-demand by the serializer
    next if current_model_class.reflect_on_attachment(key).present?

    # Check if this is a regular association
    association = current_model_class.reflect_on_association(key)
    next if association.nil?

    if value.is_a?(Hash) && value.any?
      # For polymorphic associations, we can't determine the class at compile time,
      # so we skip filtering and include the nested hash as-is
      if association.polymorphic?
        filtered[key] = value
      else
        # Recursively filter nested includes, using the associated class
        nested_class = association.klass
        nested_filtered = filter_from_includes(value, nested_class)
        filtered[key] = nested_filtered if nested_filtered.any?
      end
    else
      filtered[key] = value
    end
  end
  filtered
end

.filter_polymorphic_from_includes(includes_hash, current_model_class) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/json_api/active_storage/detection.rb', line 51

def filter_polymorphic_from_includes(includes_hash, current_model_class)
  filtered = {}

  includes_hash.each do |key, value|
    association = current_model_class.reflect_on_association(key)
    next unless association

    # Skip polymorphic associations entirely for preloading
    next if association.polymorphic?

    if value.is_a?(Hash) && value.any?
      nested_class = association.klass
      nested_filtered = filter_polymorphic_from_includes(value, nested_class)
      filtered[key] = nested_filtered if nested_filtered.any?
    else
      filtered[key] = value
    end
  end

  filtered
end