I faced this issue while developing a feature.Lets say there is following code:
case 1:
module Person
module Employee
class Officer
def self.print_class(obj)
obj.is_a? Employee
end
end
end
end
case 2:
class Person::Employee::Officer
def self.print_class(obj)
puts obj.is_a? Employee
end
end
class Employee < ActiveRecord::Base
end
emp = Employee.last
and we have model Employee . Now
For case 1: Person::Employee::Officer.print_class(emp) gives "false"
For case 2: Person::Employee::Officer.print_class(emp) gives "true"
Why is this happening?
::is the scope resolution operator. Unlike theclassandmodulekeywords it does not reopen the module and properly set the module nesting.For example:
This is because the module nesting is resolved lexically at the point of definition. When you do
module Foo::Barthat module nesting is the global scope - when you referenceTESTit is not resolved toFoo::TESTsinceFoois not in the module nesting.In your case 2
Employeeis resolved to::EmployeenotPerson::Employee.Therefore you should always explicitly nest classes and modules as it will set the correct module nesting and avoid these very unexpected module lookups.