Skip to content

Commit 805acf7

Browse files
committed
Merge pull request #181 from razum2um/develop
prevent multiple requires
2 parents c5f30d3 + e89cc7f commit 805acf7

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

lib/annotate/annotate_models.rb

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -369,10 +369,20 @@ def get_model_files(options)
369369
# Check for namespaced models in subdirectories as well as models
370370
# in subdirectories without namespacing.
371371
def get_model_class(file)
372-
# this is for non-rails projects, which don't get Rails auto-require magic
373-
require File.expand_path("#{model_dir}/#{file}")
374372
model_path = file.gsub(/\.rb$/, '')
375-
get_loaded_model(model_path) || get_loaded_model(model_path.split('/').last)
373+
begin
374+
get_loaded_model(model_path) or raise LoadError.new("cannot load a model from #{file}")
375+
rescue LoadError
376+
# this is for non-rails projects, which don't get Rails auto-require magic
377+
if Kernel.require(File.expand_path("#{model_dir}/#{model_path}"))
378+
retry
379+
elsif model_path.match(/\//)
380+
model_path = model_path.split('/')[1..-1].join('/').to_s
381+
retry
382+
else
383+
raise
384+
end
385+
end
376386
end
377387

378388
# Retrieve loaded model class by path to the file where it's supposed to be defined.

spec/annotate/annotate_models_spec.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,21 @@ class FooWithKnownMacro < ActiveRecord::Base
287287
check_class_name 'foo_with_known_macro.rb', 'FooWithKnownMacro'
288288
end.should == ""
289289
end
290+
291+
it "should not require model files twice" do
292+
create 'loaded_class.rb', <<-EOS
293+
class LoadedClass < ActiveRecord::Base
294+
CONSTANT = 1
295+
end
296+
EOS
297+
path = File.expand_path("#{AnnotateModels.model_dir}/loaded_class")
298+
Kernel.load "#{path}.rb"
299+
expect(Kernel).not_to receive(:require).with(path)
300+
301+
capturing(:stderr) {
302+
check_class_name 'loaded_class.rb', 'LoadedClass'
303+
}.should_not include("warning: already initialized constant LoadedClass::CONSTANT")
304+
end
290305
end
291306

292307
describe "#remove_annotation_of_file" do
@@ -500,6 +515,8 @@ class User < ActiveRecord::Base
500515

501516
describe "if a file can't be annotated" do
502517
before do
518+
AnnotateModels.stub(:get_loaded_model).with('user').and_return(nil)
519+
503520
write_model('user.rb', <<-EOS)
504521
class User < ActiveRecord::Base
505522
raise "oops"
@@ -528,6 +545,8 @@ class User < ActiveRecord::Base
528545

529546
describe "if a file can't be deannotated" do
530547
before do
548+
AnnotateModels.stub(:get_loaded_model).with('user').and_return(nil)
549+
531550
write_model('user.rb', <<-EOS)
532551
class User < ActiveRecord::Base
533552
raise "oops"

0 commit comments

Comments
 (0)