I am encountering a strange bug in my code. I have a rails application with the following two files in the lib:
lib/module_one/module_two/class_one.rb
module ModuleOne
module Moduletwo
class ClassOne
class << self
def test
puts 'Class one'
ClassTwo.test
end
end
end
end
end
and
lib/module_one/module_two/class_two.rb
module ModuleOne
module ModuleTwo
class ClassTwo
def self.test
puts 'Class two'
end
end
end
end
Now my problem is, that when I go into the console and write:
ModuleOne::ModuleTwo::ClassOne.test
it throws the following: NameError: uninitialized constant ClassTwo
The strange thing is, that the problem seems to be connected to the use of class << self instead of self.method. If I change the class_one.rb file like this it works!:
module ModuleOne
module ModuleTwo
class ClassOne
def self.test
puts 'Class one'
ClassTwo.test
end
end
end
end
Im loading the files in application.rb like this:
config.autoload_paths += %W(#{config.root}/lib)
Is this a bug in rails, or is it just me getting something all wrong?
Im using rails 3.1.3 btw
(Only a partial answer, but need formatting.)
It’s because of how
class << selfworks.For example, if you change it to:
it works fine.
Edit; too long for reasonable comment.
I’m poking around a bit… On an intuitive level it makes sense to me, I’m just not sure why yet. Don’t know if I knew a real reason once, or if I’m just making it up.
I’m not sure why
selfseems to refer to the module, though; the “Programming Ruby 1.9” book doesn’t go in to enough depth on theclass <<semantics. I’ll tweet something and refer to this question and someone smarter will create a real answer.