Class: SorbetRails::ModelPlugins::ActiveStorageMethods

Inherits:
Base
  • Object
show all
Defined in:
lib/sorbet-rails/model_plugins/active_storage_methods.rb

Constant Summary

Constants inherited from Base

Base::Parameter

Instance Attribute Summary

Attributes inherited from Base

#available_classes, #model_class

Instance Method Summary collapse

Methods included from SorbetRails::ModelUtils

#add_relation_query_method, #exists_class_method?, #exists_instance_method?, #model_assoc_proxy_class_name, #model_assoc_relation_class_name, #model_class, #model_class_name, #model_module_name, #model_relation_class_name, #model_relation_type_alias, #model_relation_type_class_name

Constructor Details

#initialize(model_class, available_classes) ⇒ ActiveStorageMethods

Returns a new instance of ActiveStorageMethods.



5
6
7
# File 'lib/sorbet-rails/model_plugins/active_storage_methods.rb', line 5

def initialize(model_class, available_classes)
  super
end

Instance Method Details

#create_has_many_methods(assoc_name, mod) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/sorbet-rails/model_plugins/active_storage_methods.rb', line 46

def create_has_many_methods(assoc_name, mod)
  mod.create_method(
    assoc_name,
    return_type: 'T.nilable(ActiveStorage::Attached::Many)'
  )

  mod.create_method(
    "#{assoc_name}=",
    parameters: [
      Parameter.new('*attachables', type: 'T.untyped')
    ],
    return_type: 'T.untyped'
  )
end

#create_has_one_methods(assoc_name, mod) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sorbet-rails/model_plugins/active_storage_methods.rb', line 30

def create_has_one_methods(assoc_name, mod)
  mod.create_method(
    assoc_name,
    return_type: 'T.nilable(ActiveStorage::Attached::One)'
  )

  mod.create_method(
    "#{assoc_name}=",
    parameters: [
      Parameter.new('attachable', type: 'T.untyped')
    ],
    return_type: 'T.untyped'
  )
end

#generate(root) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/sorbet-rails/model_plugins/active_storage_methods.rb', line 10

def generate(root)
  # Check that ActiveStorage the attachment_reflections method exists
  # It was added in 6.0, so it isn't available for 5.2.
  return unless defined?(@model_class.attachment_reflections) && @model_class.attachment_reflections.length > 0

  assoc_module_name = self.model_module_name("GeneratedAssociationMethods")
  assoc_module_rbi = root.create_module(assoc_module_name)

  attachment_reflections = @model_class.attachment_reflections.transform_values { |attachment| attachment.class }

  attachment_reflections.each do |assoc_name, attachment_type|
    if attachment_type.to_s == 'ActiveStorage::Reflection::HasOneAttachedReflection'
      create_has_one_methods(assoc_name, assoc_module_rbi)
    elsif attachment_type.to_s == 'ActiveStorage::Reflection::HasManyAttachedReflection'
      create_has_many_methods(assoc_name, assoc_module_rbi)
    end
  end
end