I find myself wanting to use class constants more globally in my code. Because of Ruby's encapsulation rules, every attribute (and constant) is private. A helper method exists on Module to simplify externalizing attributes:
attr, attr_accessor, attr_reader, attr_writer
I was wondering whether it would make sense to have a similar method for class constants?
const_reader
defined as follows....
# add the const_reader method to Module
class Module
def const_reader(*symbols)
symbols.each do |symbol|
class_eval "def #{self.name}.#{symbol.to_s}; #{symbol.to_s}; end"
end
end
end
# define constants and export them via const_reader:
class Airlines
AA="American Airlines"
BA="British Airways"
const_reader :AA, :BA
end
# These constants are now accessible via class methods (publicly)
# but (still) as constants internal to the class (no method overhead).
puts Airlines.AA # => "American Airlines"
puts Airlines.BA # => "British Airways"
-Rich Kilmer