Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

ruby on rails - warning: toplevel constant referenced

I have four models (Document, Question, Question::Document, and Answer). In my Answer model I have

validates :text,
  presence: { :unless => Proc.new{ |a| a.question.is_a? Question::Document } }

This gives me the the warning

warning: toplevel constant Document referenced by Question::Document

How do I prevent this warning from happening (without renaming my classes)?

question from:https://stackoverflow.com/questions/18515100/warning-toplevel-constant-referenced

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your folder/file structure should look as follows:

app/
  models/
    question/
      document.rb
    answer.rb
    document.rb
    question.rb

And then rails will automatically find the correct models (it will translate the model name to a filename, and namespaces are translated to folders).

Make sure that inside your question/document.rb the class definition looks as one of the following alternatives:

class Question::Document
end

or

class Question
  class Document
  end
end

If you write just class Document you are redefining the toplevel constant Document.

Note that if the global Document is defined first, this will also trigger this error. This depends on the code path, so the best way to resolve that, is to add a require_dependency where needed. See here and here for more background.

E.g. something like

require_dependency 'question/document' 

class Answer < ActiveRecord::Base

end  

If you put the file in a different place, where rails cannot automatically find it, you will have to explicitly require it, so rails knows Question::Document exists.

If for instance, you define Question::Document inside the Question model, which is a reasonable place, you will have to explicitly state the dependency to the Question model in your Answer model.

So, in that case, in your answer.rb you will write

require_dependency 'question'

class Answer < ActiveRecord::Base
  # ..
end

While plain require works, it is preferred to use require_dependency instead as it will work with auto-loading, which means: behaves as expected during development.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...