Skip to content

Instantly share code, notes, and snippets.

@hynkle
Last active December 11, 2015 22:09
Show Gist options
  • Save hynkle/4667870 to your computer and use it in GitHub Desktop.
Save hynkle/4667870 to your computer and use it in GitHub Desktop.
Rails constant buffoonery

Given an otherwise empty Rails app with the following two models:

# app/models/cities/massachusetts/boston.rb

class Cities::Massachusetts::Boston

  def self.refer_to_denver
    begin
      Colorado::Denver
      puts "successfully referred to Denver"
    rescue
      puts $!
    end
  end

end
# app/models/cities/colorado/denver.rb

class Cities::Colorado::Denver
end

You might expect rails runner '5.times { Cities::Massachusetts::Boston.refer_to_denver }' to produce:

successfully referred to Denver
successfully referred to Denver
successfully referred to Denver
successfully referred to Denver
successfully referred to Denver

But if you had such expectations, you would find to your bemusement that it instead produces:

successfully referred to Denver
uninitialized constant Cities::Massachusetts::Boston::Colorado
uninitialized constant Cities::Massachusetts::Boston::Colorado
uninitialized constant Cities::Massachusetts::Boston::Colorado
uninitialized constant Cities::Massachusetts::Boston::Colorado

If in the body of Cities::Massachusetts::Boston.refer_to_denver you were to refer to Denver via its fully qualified constant Cities::Colorado::Denver instead of via Colorado::Denver, you are free to call .refer_to_denver multiple times without any exceptions getting raised.

Why may I refer to Denver by its not fully qualified name precisely once?

(This was discovered in Rails 3.2.11, but presumably is not isolated to that version.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment