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

Instance Method Details

#each(&block) ⇒ Enumerator

Returns of all the registered classes.

Returns:



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.

Parameters:

  • name (String)

    Registered name of the class with optional arguments in parenthesis.

  • args

    Additional arguments to pass to the constructor. Overrides any given in the string.

Returns:

  • An instance of the registered class.



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_classesArray

Returns of names of all the registered classes.

Returns:

  • (Array)

    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.

Parameters:

  • klass (Class)

    the class to instantiate

  • name (String) (defaults to: nil)

    name to use when calling #from_name

Returns:

  • (self)


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