module CooCoo::FromName

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.

Public Instance Methods

each(&block) click to toggle source

@return [Enumerator] of all the registered classes.

# File lib/coo-coo/from_name.rb, line 26
def each(&block)
  @klasses.each(&block)
end
from_name(name, *args) click to toggle source

Returns an instance of the class registered with the given name. @param name [String] Registered name of the class with optional arguments in parenthesis. @param args Additional arguments to pass to the constructor. Overrides any given in the string. @return An instance of the registered class.

# 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() click to toggle source

@return [Array] of names of all the registered classes.

# File lib/coo-coo/from_name.rb, line 21
def named_classes
  @klasses.keys.sort
end
register(klass, name = nil) click to toggle source

Adds a class to the registry using the given name. @param klass [Class] the class to instantiate @param name [String] name to use when calling from_name @return [self]

# 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

Private Instance Methods

parse_name(name) click to toggle source
# File lib/coo-coo/from_name.rb, line 49
def parse_name(name)
  m = name.match(/(\w+)\((.*)\)/)
  if m
    return m[1], m[2].split(',').collect(&:chomp)
  else
    return name, nil
  end
end