@@ -711,11 +711,11 @@ def get_model_class(file)
711
711
model_path = file . gsub ( /\. rb$/ , '' )
712
712
model_dir . each { |dir | model_path = model_path . gsub ( /^#{ dir } / , '' ) . gsub ( /^\/ / , '' ) }
713
713
begin
714
- get_loaded_model ( model_path ) || raise ( BadModelFileError . new )
714
+ get_loaded_model ( model_path , file ) || raise ( BadModelFileError . new )
715
715
rescue LoadError
716
716
# this is for non-rails projects, which don't get Rails auto-require magic
717
717
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 )
719
719
retry
720
720
elsif model_path =~ /\/ /
721
721
model_path = model_path . split ( '/' ) [ 1 ..-1 ] . join ( '/' ) . to_s
@@ -726,8 +726,24 @@ def get_model_class(file)
726
726
end
727
727
end
728
728
729
+ # Retrieve loaded model class
730
+ def get_loaded_model ( model_path , file )
731
+ loaded_model_class = get_loaded_model_by_path ( model_path )
732
+ return loaded_model_class if loaded_model_class
733
+
734
+ # We cannot get loaded model when `model_path` is loaded by Rails
735
+ # auto_load/eager_load paths. Try all possible model paths one by one.
736
+ absolute_file = File . expand_path ( file )
737
+ model_paths =
738
+ $LOAD_PATH. select { |path | absolute_file . include? ( path ) }
739
+ . map { |path | absolute_file . sub ( path , '' ) . sub ( /\. rb$/ , '' ) . sub ( /^\/ / , '' ) }
740
+ model_paths
741
+ . map { |path | get_loaded_model_by_path ( path ) }
742
+ . find { |loaded_model | !loaded_model . nil? }
743
+ end
744
+
729
745
# Retrieve loaded model class by path to the file where it's supposed to be defined.
730
- def get_loaded_model ( model_path )
746
+ def get_loaded_model_by_path ( model_path )
731
747
ActiveSupport ::Inflector . constantize ( ActiveSupport ::Inflector . camelize ( model_path ) )
732
748
rescue StandardError , LoadError
733
749
# Revert to the old way but it is not really robust
@@ -858,15 +874,6 @@ def classified_sort(cols)
858
874
( [ id ] << rest_cols << timestamps << associations ) . flatten . compact
859
875
end
860
876
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
-
870
877
private
871
878
872
879
def with_comments? ( klass , options )
0 commit comments