Class: AnnotateRb::ModelAnnotator::ModelClassGetter

Inherits:
Object
  • Object
show all
Defined in:
lib/annotate_rb/model_annotator/model_class_getter.rb

Class Method Summary collapse

Class Method Details

.call(file, options) ⇒ Object

Retrieve the classes belonging to the model names we’re asked to process Check for namespaced models in subdirectories as well as models in subdirectories without namespacing.



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
# File 'lib/annotate_rb/model_annotator/model_class_getter.rb', line 10

def call(file, options)
  use_zeitwerk = defined?(::Rails) && ::Rails.try(:autoloaders).try(:zeitwerk_enabled?)

  if use_zeitwerk
    klass = ZeitwerkClassGetter.call(file, options)
    return klass if klass
  end

  model_path = file.gsub(/\.rb$/, "")
  options[:model_dir].each { |dir| model_path = model_path.gsub(/^#{dir}/, "").gsub(/^\//, "") }

  begin
    get_loaded_model(model_path, file) || raise(BadModelFileError.new)
  rescue LoadError
    # this is for non-rails projects, which don't get Rails auto-require magic
    file_path = File.expand_path(file)
    if File.file?(file_path) && Kernel.require(file_path)
      retry
    elsif /\//.match?(model_path)
      model_path = model_path.split("/")[1..-1].join("/").to_s
      retry
    else
      raise
    end
  end
end