Skip to content

Commit 3af2d00

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 3af2d00

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,7 @@ class Foo < ActiveRecord::Base
20742074

20752075
let :file_content_2 do
20762076
<<-EOS
2077-
class Bar::Foo
2077+
class Bar::Foo < ActiveRecord::Base
20782078
end
20792079
EOS
20802080
end
@@ -2089,6 +2089,39 @@ class Bar::Foo
20892089
end
20902090
end
20912091

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+
'foo/bar.rb'
2106+
end
2107+
2108+
let :file_content_2 do
2109+
<<-EOS
2110+
class Foo::Bar < ActiveRecord::Base
2111+
end
2112+
EOS
2113+
end
2114+
2115+
let :klass_2 do
2116+
AnnotateModels.get_model_class(File.join(AnnotateModels.model_dir[0], filename_2))
2117+
end
2118+
2119+
it 'finds valid model' do
2120+
expect(klass.name).to eq('Foo')
2121+
expect(klass_2.name).to eq('Foo::Bar')
2122+
end
2123+
end
2124+
20922125
context 'one of the classes is nested in another class' do
20932126
let :filename do
20942127
'voucher.rb'
@@ -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)