I am working on a Ruby on Rails 6 project, and I am trying to use a class instance variable on an ActiveRecord model. 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
. There are multiple such models, each of them referring to a different AnotherClass
, with all the AnotherClass
es being subclasses of some BaseClass
.
However, I am encountering the following error:
uninitialized constant Model::AnotherClass
Because of the class << self
, Ruby seems to be looking for a nested class.
Is there a way to access AnotherClass
directly, or is there a better way in general to set this up?
Edit: I solved this with a completely different approach, however I'm still interested to see how you would get around this issue.