Module: Collection::Generic

Defined in:
lib/collection/generic.rb

Instance Method Summary collapse

Instance Method Details

#[](type_parameter) ⇒ Object


3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/collection/generic.rb', line 3

def [](type_parameter)
  type_parameter_name = constant_name(type_parameter)

  cls = nil
  unless self.const_defined?(type_parameter_name, false)
    cls = define_class(type_parameter)
    set_collection_constant(type_parameter, cls)
  else
    cls = const_get(type_parameter_name)
  end

  cls
end

#constant_name(constant) ⇒ Object


31
32
33
# File 'lib/collection/generic.rb', line 31

def constant_name(constant)
  constant.name.gsub('::', '_')
end

#define_class(type_parameter) ⇒ Object


17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/collection/generic.rb', line 17

def define_class(type_parameter)
  cls = Class.new(self) do
    def initialize; end

    define_method :type_parameter do
      type_parameter
    end
  end

  set_collection_constant(type_parameter, cls)

  cls
end

#set_collection_constant(constant, cls) ⇒ Object


35
36
37
38
39
40
41
42
43
# File 'lib/collection/generic.rb', line 35

def set_collection_constant(constant, cls)
  class_name = constant_name(constant)

  unless self.const_defined?(class_name, false)
    self.const_set(class_name, cls)
  end

  class_name
end