What is the right way to initialize a constant in Ruby? What is the right way to initialize a constant in Ruby? ruby ruby

What is the right way to initialize a constant in Ruby?


The only way this can happen, is when bar.rb is required multiple times. Which shouldn't happen, since require doesn't load files that have already been loaded once.

It does, however, only use the path you pass to it to determine whether a file has already been loaded, at least in Ruby 1.8:

require 'bar'   # => true, file was loadedrequire 'bar'   # => false, file had already been loadedrequire './bar' # => true, OOPS, I DID IT AGAIN# bar.rb:3: warning: already initialized constant BAZ

So, you are right: this could very well be an indication that there is something wrong with your dependency management.

Typical warning signs are

  • manually constructing file paths instead of just relying on $LOAD_PATH

    require "File.expand_path('../lib/bar', File.dirname(__FILE__))"
  • manipulating $LOAD_PATH anywhere except maybe the main entry point to your library:

    path = File.expand_path(File.dirname(__FILE__))$LOAD_PATH << path unless $LOAD_PATH.include?(path)

In general, my philosophy is that it's not my job as a library writer to figure out how to put my library on the $LOAD_PATH. It's the system administrator's job. If the sysadmin uses RubyGems to install my library, then RubyGems will take care of it, otherwise whatever other package management system he uses should take care of it, and if he uses setup.rb, then it will be installed in site_ruby, which is already on the $LOAD_PATH anyway.


There's a good discussion on this in the comments on this post. I think the following one puts it nicely:

This irked me somewhat when I first walked up to Ruby. It was a remnant of my static type brainwashing. Three things mitigate against this being a real problem. 1. The warning. You could argue it should be an exception, but in reality, how would that be any different in the case where some other programmer silently caught the exception? Which brings me to number 2) Don't work with morons. Only morons silently catch exceptions and continue and only morons change constant values used in that way. Which brings me to 3) Neither of us is a moron, so you'll be happy to know that anecdotally this has never happened to me. It's really because constants stand out in Ruby anyway, what with their upcase, and how often are you likely to have a constant as an L-value in your code?

To directly answer your question, I wouldn't do anything to get rid of the warning. Just take the warning as just that, a warning, and move on.