Class: SorbetRails::ModelPlugins::ActiveRecordNamedScope

Inherits:
Base
  • Object
show all
Defined in:
lib/sorbet-rails/model_plugins/active_record_named_scope.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 inherited from Base

#initialize, #serialization_coder_for_column

Methods included from SorbetRails::ModelUtils

#add_relation_query_method, #exists_class_method?, #exists_instance_method?, #habtm_class?, #model_assoc_proxy_class_name, #model_assoc_relation_class_name, #model_class_name, #model_module_name, #model_query_methods_returning_assoc_relation_module_name, #model_query_methods_returning_relation_module_name, #model_relation_class_name, #model_relation_type_alias, #model_relation_type_class_name

Methods included from SorbetRails::ModelColumnUtils

#active_record_type_to_sorbet_type, #attribute_has_unconditional_presence_validation?, #model_class, #nilable_column?, #time_zone_aware_column?, #type_for_column_def

Constructor Details

This class inherits a constructor from SorbetRails::ModelPlugins::Base

Instance Method Details

#generate(root) ⇒ Object


7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sorbet-rails/model_plugins/active_record_named_scope.rb', line 7

def generate(root)
  model_class_rbi = root.create_class(self.model_class_name)

  # Named scope methods are dynamically defined by the `scope` method so their
  # source_location is `lib/active_record/scoping/named.rb`. So we find scopes
  # by two criteria:
  # - they are defined in 'activerecord/lib/active_record/scoping/named.rb'
  # - they are not one of the methods actually defined in that file's source.
  # See: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/scoping/named.rb
  non_dynamic_methods = (
    ActiveRecord::Scoping::Named::ClassMethods.instance_methods +
    ActiveRecord::Scoping::Named::ClassMethods.protected_instance_methods +
    ActiveRecord::Scoping::Named::ClassMethods.private_instance_methods
  )

  (@model_class.methods - non_dynamic_methods).sort.each do |method_name|
    next unless SorbetRails::Utils.valid_method_name?(method_name.to_s)

    method_obj = @model_class.method(method_name)
    next unless method_obj.present? && method_obj.source_location.present?

    source_file = method_obj.source_location[0]
    next unless source_file.include?("lib/active_record/scoping/named.rb")

    add_relation_query_method(
      root,
      method_name.to_s,
      parameters: [
        Parameter.new("*args", type: "T.untyped"),
      ],
    )
  end
end