Skip to content

Commit ade7582

Browse files
committed
Only return valid models from get_loaded_model
This avoids cases where you have: ``` module Foobar; end; class A class Foobar; end end ``` And get_loaded_model returns Foobar even though it isn't the right thing to do. This was a case I ran into where the base module was autogenerated.
1 parent 3d2a65b commit ade7582

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

lib/annotate/annotate_models.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,9 @@ def get_loaded_model(model_path, file)
602602

603603
# Retrieve loaded model class by path to the file where it's supposed to be defined.
604604
def get_loaded_model_by_path(model_path)
605-
ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path))
605+
klass = ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path))
606+
607+
klass if klass.is_a?(Class) && klass < ActiveRecord::Base
606608
rescue StandardError, LoadError
607609
# Revert to the old way but it is not really robust
608610
ObjectSpace.each_object(::Class)

spec/lib/annotate/annotate_models_spec.rb

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2074,7 +2074,40 @@ class Foo < ActiveRecord::Base
20742074

20752075
let :file_content_2 do
20762076
<<-EOS
2077-
class Bar::Foo
2077+
class Bar::Foo < ActiveRecord::Base
2078+
end
2079+
EOS
2080+
end
2081+
2082+
let :klass_2 do
2083+
AnnotateModels.get_model_class(File.join(AnnotateModels.model_dir[0], filename_2))
2084+
end
2085+
2086+
it 'finds valid model' do
2087+
expect(klass.name).to eq('Foo')
2088+
expect(klass_2.name).to eq('Bar::Foo')
2089+
end
2090+
end
2091+
2092+
context 'the class name and base name clash' do
2093+
let :filename do
2094+
'foo.rb'
2095+
end
2096+
2097+
let :file_content do
2098+
<<-EOS
2099+
class Foo < ActiveRecord::Base
2100+
end
2101+
EOS
2102+
end
2103+
2104+
let :filename_2 do
2105+
'bar/foo.rb'
2106+
end
2107+
2108+
let :file_content_2 do
2109+
<<-EOS
2110+
class Bar::Foo < ActiveRecord::Base
20782111
end
20792112
EOS
20802113
end
@@ -2108,7 +2141,7 @@ class Voucher < ActiveRecord::Base
21082141
let :file_content_2 do
21092142
<<~EOS
21102143
class Voucher
2111-
class Foo
2144+
class Foo < ActiveRecord::Base
21122145
end
21132146
end
21142147
EOS

0 commit comments

Comments
 (0)