Module: Collection::Generic
- Defined in:
- lib/collection/generic.rb
Instance Method Summary collapse
- #[](type_parameter, &implementation) ⇒ Object
- #constant_name(constant) ⇒ Object
- #define_class(type_parameter, &implementation) ⇒ Object
- #set_collection_constant(constant, cls, randomize = nil) ⇒ Object
Instance Method Details
#[](type_parameter, &implementation) ⇒ Object
3 4 5 6 7 8 9 10 11 |
# File 'lib/collection/generic.rb', line 3 def [](type_parameter, &implementation) type_parameter_name = constant_name(type_parameter) if implementation.nil? && self.const_defined?(type_parameter_name, false) return const_get(type_parameter_name) else return define_class(type_parameter, &implementation) end end |
#constant_name(constant) ⇒ Object
57 58 59 |
# File 'lib/collection/generic.rb', line 57 def constant_name(constant) constant.name.gsub('::', '_') end |
#define_class(type_parameter, &implementation) ⇒ Object
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 |
# File 'lib/collection/generic.rb', line 13 def define_class(type_parameter, &implementation) cls = Class.new(self) do def self.build(items) instance = new items.each do |member| instance.add(member) end instance end def initialize; end define_method :type_parameter do type_parameter end end if not implementation.nil? cls.class_exec(&implementation) end randomize = !implementation.nil? set_collection_constant(type_parameter, cls, randomize) cls end |
#set_collection_constant(constant, cls, randomize = nil) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/collection/generic.rb', line 42 def set_collection_constant(constant, cls, randomize=nil) randomize ||= false constant_name = constant_name(constant) if randomize suffix = SecureRandom.hex.upcase constant_name = "#{constant_name}_#{suffix}" end self.const_set(constant_name, cls) constant_name end |