[英]How to initialize Ruby class instance variable to a new instance of another class?
I am working on a Ruby on Rails 6 project, and I am trying to use a class instance variable on an ActiveRecord model.我正在开发 Rails 6 项目上的 Ruby,并且我正在尝试在 ActiveRecord Z20F35E680FDAF399 上使用class 实例变量Here is a basic example:
这是一个基本示例:
class Model << ApplicationRecord
@var = AnotherClass.new
class << self
attr_reader :var
end
# ...
end
I would then like to be able to use Model.var
to access Model
's instance of AnotherClass
.然后我希望能够使用
Model.var
来访问Model
的AnotherClass
实例。 There are multiple such models, each of them referring to a different AnotherClass
, with all the AnotherClass
es being subclasses of some BaseClass
.有多个这样的模型,每个模型都引用一个不同的
AnotherClass
,所有的AnotherClass
都是一些BaseClass
的子类。
However, I am encountering the following error:但是,我遇到以下错误:
uninitialized constant Model::AnotherClass
未初始化常量 Model::AnotherClass
Because of the class << self
, Ruby seems to be looking for a nested class.由于
class << self
, Ruby 似乎正在寻找嵌套的 class。
Is there a way to access AnotherClass
directly, or is there a better way in general to set this up?有没有办法直接访问
AnotherClass
,还是有更好的方法来设置它?
Edit : I solved this with a completely different approach, however I'm still interested to see how you would get around this issue.编辑:我用完全不同的方法解决了这个问题,但是我仍然有兴趣看看你将如何解决这个问题。
The error you receive:您收到的错误:
uninitialized constant Model::AnotherClass
未初始化常量 Model::AnotherClass
Tells you that AnotherClass
is not initialized (not loaded/found).告诉您
AnotherClass
未初始化(未加载/找到)。 Let me use the following context as an example:让我以以下上下文为例:
class Model
AnotherClass
end
Ruby will start a constant lookup. Ruby 将开始持续查找。 This will start from the current namespace (
Model
) and and if nothing is found move up into the namespace tree.这将从当前命名空间 (
Model
) 开始,如果没有找到任何内容,则向上移动到命名空间树中。 In the above example it will first look for Model::AnotherClass
if that cannot be found it will look for AnotherClass
, if that cannot be found it will throw the exception you receive.在上面的示例中,它将首先查找
Model::AnotherClass
如果找不到,它将查找AnotherClass
,如果找不到,它将抛出您收到的异常。
This error simply tells you that AnotherClass
is not loaded.此错误只是告诉您未加载
AnotherClass
。
Anything in th app/
directory is loaded by the autoloader of Rails, however if you use the lib/
directory you have to manually require 'another_class'
or add the relevant path to the autoload paths . app/
目录中的任何内容都由 Rails 的自动加载器加载,但是如果您使用lib/
目录,则必须手动require 'another_class'
或将相关路径添加到自动加载路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.