Skip to content

Commit 8056ecf

Browse files
author
Cuong Tran
committed
Fix the conversion from file path to class name which should fix #125 and #141
1 parent 2b34d60 commit 8056ecf

File tree

2 files changed

+44
-7
lines changed

2 files changed

+44
-7
lines changed

lib/annotate/annotate_models.rb

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -377,13 +377,18 @@ def get_model_class(file)
377377

378378
# Retrieve loaded model class by path to the file where it's supposed to be defined.
379379
def get_loaded_model(model_path)
380-
ObjectSpace.each_object(::Class).
381-
select do |c|
382-
Class === c and # note: we use === to avoid a bug in activesupport 2.3.14 OptionMerger vs. is_a?
383-
c.ancestors.respond_to?(:include?) and # to fix FactoryGirl bug, see https://github.com/ctran/annotate_models/pull/82
384-
c.ancestors.include?(ActiveRecord::Base)
385-
end.
386-
detect { |c| ActiveSupport::Inflector.underscore(c) == model_path }
380+
begin
381+
ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path))
382+
rescue
383+
# Revert to the old way but it is not really robust
384+
ObjectSpace.each_object(::Class).
385+
select do |c|
386+
Class === c and # note: we use === to avoid a bug in activesupport 2.3.14 OptionMerger vs. is_a?
387+
c.ancestors.respond_to?(:include?) and # to fix FactoryGirl bug, see https://github.com/ctran/annotate_models/pull/82
388+
c.ancestors.include?(ActiveRecord::Base)
389+
end.
390+
detect { |c| ActiveSupport::Inflector.underscore(c) == model_path }
391+
end
387392
end
388393

389394
# We're passed a name of things that might be

spec/annotate/annotate_models_spec.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,38 @@ class FooInsideBar < ActiveRecord::Base
182182
check_class_name 'bar/foo_inside_bar.rb', 'Bar::FooInsideBar'
183183
end
184184

185+
it "should find AR model when duplicated by a nested model" do
186+
create 'foo.rb', <<-EOS
187+
class Foo < ActiveRecord::Base
188+
end
189+
EOS
190+
191+
create 'bar/foo.rb', <<-EOS
192+
class Bar::Foo
193+
end
194+
EOS
195+
check_class_name 'bar/foo.rb', 'Bar::Foo'
196+
check_class_name 'foo.rb', 'Foo'
197+
end
198+
199+
it "should find AR model nested inside a class" do
200+
create 'voucher.rb', <<-EOS
201+
class Voucher < ActiveRecord::Base
202+
end
203+
EOS
204+
205+
create 'voucher/foo.rb', <<-EOS
206+
class Voucher
207+
class Foo
208+
end
209+
end
210+
EOS
211+
212+
check_class_name 'voucher.rb', 'Voucher'
213+
check_class_name 'voucher/foo.rb', 'Voucher::Foo'
214+
end
215+
216+
185217
it "should not care about unknown macros" do
186218
create 'foo_with_macro.rb', <<-EOS
187219
class FooWithMacro < ActiveRecord::Base

0 commit comments

Comments
 (0)