module Rubenum

Rubenum allows you to create simple enumerations in Ruby.

Public Class Methods

new(elements, upcase: false, binary_values: false) click to toggle source

Create a new enumeration from an array of strings with `Rubenum.new`.

Only valid Ruby identifiers are accepted.

By default, every element will be capitalized in order to make valid Ruby constant identifiers.

Arguments :

  • elements (array of string) : array containing the elements of the enumeration

  • upcase (optional boolean (default : false)) : true => upcase the elements' name instead of capitalizing them

  • binary_values (optional boolean (default : false)) : true => use binary values (1 2 4 8 16 …) instead of incremental values (1 2 3 4 5 …)

Example :

colors = Rubenum.new(%w[red orange green])
puts colors::Orange   # => 2
# File lib/rubenum.rb, line 15
def self.new(elements, upcase: false, binary_values: false)
        Module.new do |mod|
                raise ArgumentError, "<elements> must be an array" unless elements.is_a?(Array)
                raise ArgumentError, "<elements> can't be empty" if elements.empty?

                # Format the elements and remove duplicates
                cleaned_elements = elements.map do |e|
                        raise ArgumentError, "<elements> must only contain strings" unless e.is_a?(String)
                        upcase ? e.upcase : e.capitalize
                end
                cleaned_elements.uniq!

                cleaned_elements.each_with_index do |e, i|
                        # Calculate the value of the element
                        value = 1
                        if binary_values
                                value <<= i
                        else
                                value += i
                        end

                        # Add the element to the enumeration
                        mod.const_set(e, value)
                end

                # Freeze the module so it can't be modified
                mod.freeze
        end
end