Module: Rubenum

Defined in:
lib/rubenum.rb

Overview

Rubenum allows you to create simple enumerations in Ruby.

Class Method Summary collapse

Class Method Details

.new(elements, upcase: false, binary_values: false) ⇒ Object

puts colors::Orange # => 2



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 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