Created
April 14, 2011 19:41
-
-
Save thegorgon/920307 to your computer and use it in GitHub Desktop.
Sometimes you want enumerable style uniqueness in class constants. This raises an error if two constants are defined with the same value.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DuplicateConstantError < StandardError; end | |
module UniqConstants | |
def uniq_constants! | |
values = constants.group_by { |c| const_get(c) } | |
dupes = values.values.select { |a| a.length > 1 } | |
raise DuplicateConstantError, "Duplicate constants defined : #{dupes.flatten.inspect}" if dupes.present? | |
end | |
end | |
# Example : | |
# | |
# class Event | |
# CONSTANT_ONE = 1 | |
# CONSTANT_TWO = 2 | |
# DUPLICATE_CONSTANT = 2 | |
# uniq_constants! | |
# end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment