Quick Answer
Fix missing constant references.
Understanding the Issue
This error occurs when Ruby cannot find a class, module, or other constant. Common causes include typos, missing requires, or incorrect scoping.
The Problem
This code demonstrates the issue:
Ruby
Error
Person.new # NameError if Person undefined
The Solution
Here's the corrected code:
Ruby
Fixed
# Solution 1: Require needed files
require "person"
# Solution 2: Check class existence
if defined?(Person)
Person.new
end
# Solution 3: Absolute namespace reference
::Person.new # From root namespace
# Solution 4: Autoloading (Rails)
# config/initializers/autoload.rb
# Rails.autoloaders.each do |autoloader|
# autoloader.preload "app/models/person.rb"
# end
Key Takeaways
Ensure proper file loading and namespace resolution.