Module: Enumeration::ClassMethods

Defined in:
lib/enumeration.rb

Instance Method Summary collapse

Instance Method Details

#enum(name, map_or_list) ⇒ Object



7
8
9
10
11
12
13
14
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
# File 'lib/enumeration.rb', line 7

def enum(name, map_or_list)
  # TODO: validate name
  c = Collection.new(map_or_list)

  # define an anonymous Module to extend on
  # defining a class level map reader
  class_methods = Module.new do
    define_method(name.to_s+'_collection') { c.data }
    define_method(name.to_s+'_set') { c.set }
    define_method(name) {|k| class_variable_get("@@#{name}")[k]} if c.map?
  end

  # set a class variable to store the enum map (used by above reader)
  # extend the anonymous module to get tne above class
  #   level reader for the map
  class_eval do
    class_variable_set("@@#{name}", c)
    extend class_methods
  end

  # instance writer for the enum value
  define_method("#{name}=") do |value|
    c = self.class.send(:class_variable_get, "@@#{name}")
    instance_variable_set("@#{name}", c[value])
  end

  # instance reader for the enum value
  define_method(name) { instance_variable_get("@#{name}") }

  # instance reader for the enum key
  define_method(name.to_s+'_key') do
    c = self.class.send(:class_variable_get, "@@#{name}")
    c.key(instance_variable_get("@#{name}"))
  end
end