Module: CooCoo::FromName
- Included in:
- ActivationFunctions, CostFunctions
- Defined in:
- lib/coo-coo/from_name.rb
Overview
Adds class methods to register classes that can be instantiated using strings.
To get an instance, use #from_name.
To add classes to the registry, call #register, preferably inside the class definition.
Instance Method Summary collapse
-
#each(&block) ⇒ Enumerator
Of all the registered classes.
-
#from_name(name, *args) ⇒ Object
Returns an instance of the class registered with the given name.
-
#named_classes ⇒ Array
Of names of all the registered classes.
-
#register(klass, name = nil) ⇒ self
Adds a class to the registry using the given name.
Instance Method Details
#each(&block) ⇒ Enumerator
Returns of all the registered classes.
26 27 28 |
# File 'lib/coo-coo/from_name.rb', line 26 def each(&block) @klasses.each(&block) end |
#from_name(name, *args) ⇒ Object
Returns an instance of the class registered with the given name.
34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/coo-coo/from_name.rb', line 34 def from_name(name, *args) name, params = parse_name(name) klass = @klasses.fetch(name) params = args unless args == nil || args.empty? if params && klass.respond_to?(:new) klass.new(*params) elsif klass.respond_to?(:instance) klass.instance else klass end end |
#named_classes ⇒ Array
Returns of names of all the registered classes.
21 22 23 |
# File 'lib/coo-coo/from_name.rb', line 21 def named_classes @klasses.keys.sort end |
#register(klass, name = nil) ⇒ self
Adds a class to the registry using the given name.
14 15 16 17 18 |
# File 'lib/coo-coo/from_name.rb', line 14 def register(klass, name = nil) @klasses ||= Hash.new @klasses[(name || klass.name).split('::').last] = klass self end |