What is the right way to initialize a constant in Ruby?
- by zbrimhall
I have a simple class that defines some constants, e.g.:
module Foo
class Bar
BAZ = "bof"
...
Everything is puppies and rainbows until I tell Rake to run all my Test::Unit tests. When it does, I get warnings:
bar.rb:3: warning: already initialized constant BAZ
My habit has been to avoid these warnings by making the constant initialization conditional, e.g.:
...
BAZ = "bof" unless const_defined? :BAZ
...
This seems to solve the problem, but it is a little tedious, and I don't ever see anyone else initializing constants this way. This makes me think I might be Doing It Wrong. Is there a better way to initialize constants that won't generate warnings?