Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Only return valid models from get_loaded_model_by_path #801

Merged
merged 2 commits into from
May 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ Into environment gems from Github checkout:

git clone https://github.com/ctran/annotate_models.git annotate_models
cd annotate_models
rake build
gem install pkg/annotate-*.gem
rake gem
gem install dist/annotate-*.gem

## Usage

Expand Down
4 changes: 3 additions & 1 deletion lib/annotate/annotate_models.rb
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,9 @@ def get_loaded_model(model_path, file)

# Retrieve loaded model class by path to the file where it's supposed to be defined.
def get_loaded_model_by_path(model_path)
ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path))
klass = ActiveSupport::Inflector.constantize(ActiveSupport::Inflector.camelize(model_path))

klass if klass.is_a?(Class) && klass < ActiveRecord::Base
rescue StandardError, LoadError
# Revert to the old way but it is not really robust
ObjectSpace.each_object(::Class)
Expand Down
37 changes: 35 additions & 2 deletions spec/lib/annotate/annotate_models_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2074,7 +2074,40 @@ class Foo < ActiveRecord::Base

let :file_content_2 do
<<-EOS
class Bar::Foo
class Bar::Foo < ActiveRecord::Base
end
EOS
end

let :klass_2 do
AnnotateModels.get_model_class(File.join(AnnotateModels.model_dir[0], filename_2))
end

it 'finds valid model' do
expect(klass.name).to eq('Foo')
expect(klass_2.name).to eq('Bar::Foo')
end
end

context 'the class name and base name clash' do
let :filename do
'foo.rb'
end

let :file_content do
<<-EOS
class Foo < ActiveRecord::Base
end
EOS
end

let :filename_2 do
'bar/foo.rb'
end

let :file_content_2 do
<<-EOS
class Bar::Foo < ActiveRecord::Base
end
EOS
end
Expand Down Expand Up @@ -2108,7 +2141,7 @@ class Voucher < ActiveRecord::Base
let :file_content_2 do
<<~EOS
class Voucher
class Foo
class Foo < ActiveRecord::Base
end
end
EOS
Expand Down