Skip to content

Instantly share code, notes, and snippets.

@thegorgon
Created April 14, 2011 19:41
Show Gist options
  • Save thegorgon/920307 to your computer and use it in GitHub Desktop.
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.
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