Module: EnumerableConstants

Overview

MyEnumeration.next_const_value # 6

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object

This is the method that injects the new static-scope routines.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/enumerable_constants.rb', line 48

def self.included(base)
  base.module_eval do

    ##
    # Return the defined constants in a hash keyed by name.
    def self.by_name
      result = {}
      self.constants.each do |constant|
        result[constant] = self.const_get(constant)
      end
      return result
    end
    
    # Return the defined constants in a hash keyed by value.
    def self.by_value
      result = {}
      self.constants.each do |constant|
        result[self.const_get(constant)] = constant          
      end
      return result
    end
    
    # This routine returns a flattened array of alternating symbols and values.
    # The symbols are the CONSTANT names and values are the values defined by that constant.
    def self.flatten_consts
      by_name.to_a.flatten
    end

    ##
    # Get the last defined value.
    def self.last_const_value
      if self.constants.empty?
        return 0
      else
        return self.const_get(self.constants.last)
      end
    end

    ##
    # Get the next value in order.
    def self.next_const_value
      last_const_value.next
    end

    def self.const_missing(const)
      self.const_set(const, next_const_value)
    end
  end
end