Skip to content

Commit 224fce3

Browse files
author
0x01f7
committed
Fix ctran#281: "already initialized constant" warnings when models are in additional configured auto load roots
1 parent 1d6e269 commit 224fce3

File tree

1 file changed

+12
-11
lines changed

1 file changed

+12
-11
lines changed

lib/annotate/annotate_models.rb

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -711,11 +711,11 @@ def get_model_class(file)
711711
model_path = file.gsub(/\.rb$/, '')
712712
model_dir.each { |dir| model_path = model_path.gsub(/^#{dir}/, '').gsub(/^\//, '') }
713713
begin
714-
get_loaded_model(model_path) || raise(BadModelFileError.new)
714+
get_loaded_model_properly(model_path, file) || raise(BadModelFileError.new)
715715
rescue LoadError
716716
# this is for non-rails projects, which don't get Rails auto-require magic
717717
file_path = File.expand_path(file)
718-
if File.file?(file_path) && silence_warnings { Kernel.require(file_path) }
718+
if File.file?(file_path) && Kernel.require(file_path)
719719
retry
720720
elsif model_path =~ /\//
721721
model_path = model_path.split('/')[1..-1].join('/').to_s
@@ -726,6 +726,16 @@ def get_model_class(file)
726726
end
727727
end
728728

729+
#
730+
def get_loaded_model_properly(model_path, file)
731+
klass = get_loaded_model(model_path)
732+
return klass if klass
733+
734+
absolute_file = File.expand_path(file)
735+
model_paths = $LOAD_PATH.select { |load_path| absolute_file.include?(load_path) }.map { |load_path| absolute_file.sub(load_path, '').sub(/^\//, '').sub(/\.rb$/, '') }
736+
model_paths.map { |model_path| get_loaded_model(model_path) }.find { |loaded_model| !loaded_model.nil? }
737+
end
738+
729739
# Retrieve loaded model class by path to the file where it's supposed to be defined.
730740
def get_loaded_model(model_path)
731741
ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path))
@@ -858,15 +868,6 @@ def classified_sort(cols)
858868
([id] << rest_cols << timestamps << associations).flatten.compact
859869
end
860870

861-
# Ignore warnings for the duration of the block ()
862-
def silence_warnings
863-
old_verbose = $VERBOSE
864-
$VERBOSE = nil
865-
yield
866-
ensure
867-
$VERBOSE = old_verbose
868-
end
869-
870871
private
871872

872873
def with_comments?(klass, options)

0 commit comments

Comments
 (0)