Module: Renum::EnumeratedValueTypeFactory

Defined in:
lib/renum/enumerated_value_type_factory.rb

Class Method Summary collapse

Class Method Details

.create(nest, type_name, values, &block) ⇒ Object



6
7
8
9
# File 'lib/renum/enumerated_value_type_factory.rb', line 6

def create nest, type_name, values, &block
  klass = create_class nest, type_name
  create_values klass, values, &block
end

.create_class(nest, type_name) ⇒ Object



11
12
13
14
15
# File 'lib/renum/enumerated_value_type_factory.rb', line 11

def create_class nest, type_name
  klass = Class.new EnumeratedValue
  nest.const_set(type_name, klass)
  klass
end

.create_values(klass, values, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/renum/enumerated_value_type_factory.rb', line 17

def create_values klass, values, &block
  setup_for_definition_in_block(klass) if values == :defined_in_block
  klass.class_eval &block if block_given?
  if values == :defined_in_block
    klass.block_defined_values.each do |value_name, init_args, instance_block|
      value = klass.new(value_name)
      klass.const_set(value_name, value)
      value.instance_eval &instance_block if instance_block
      value.init *init_args if value.respond_to? :init
    end
    teardown_from_definition_in_block(klass)
  else
    values.each do |name|
      klass.const_set(name, klass.new(name))
    end
  end
  klass.values.freeze
end

.setup_for_definition_in_block(klass) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/renum/enumerated_value_type_factory.rb', line 36

def setup_for_definition_in_block klass
  klass.class_eval do
    def self.block_defined_values
      @block_defined_values ||= []
    end

    def self.method_missing value_name, *init_args, &instance_block
      block_defined_values << [value_name, init_args, instance_block]
    end
  end
end

.teardown_from_definition_in_block(klass) ⇒ Object



48
49
50
51
52
53
# File 'lib/renum/enumerated_value_type_factory.rb', line 48

def teardown_from_definition_in_block klass
  class << klass
    remove_method :block_defined_values
    remove_method :method_missing
  end
end