Class: MetaBuilder::Factories::UniqueFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/MetaBuilder/factory.rb

Overview

A factory for which there is only one instance of each class described, and only one selected instance at any moment. User can switch freely from one instance to another.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_class, default = nil) ⇒ UniqueFactory

Creates a UniqueFactory using the factory in base_class. The selected description is named by default, or is the first one in the list in case default is missing.



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/MetaBuilder/factory.rb', line 41

def initialize(base_class, default = nil)
  @base_class = base_class
  @instances = {}
  for name, desc in @base_class.factory_description_hash
    @instances[name] = desc.instantiate
  end
  if default.nil?
    default = @base_class.factory_description_list.first.name
  end
  self.current=default
end

Instance Attribute Details

#currentObject

Returns the value of attribute current.



36
37
38
# File 'lib/MetaBuilder/factory.rb', line 36

def current
  @current
end

#current_nameObject (readonly)

Returns the value of attribute current_name.



36
37
38
# File 'lib/MetaBuilder/factory.rb', line 36

def current_name
  @current_name
end

Instance Method Details

#instance(name) ⇒ Object

Returns the instance of the named class name, and sets the current class as a side effect.



73
74
75
76
# File 'lib/MetaBuilder/factory.rb', line 73

def instance(name)
  self.current = name
  return @current
end

#instance_listObject



63
64
65
# File 'lib/MetaBuilder/factory.rb', line 63

def instance_list
  return @instances.values
end

#instancesObject



67
68
69
# File 'lib/MetaBuilder/factory.rb', line 67

def instances
  return @instances
end

#option_parser_factory(parser, banner = "", uniquify = true) ⇒ Object

Fills the Optionparser parser with all the options necessary to select a class among others and set options to it. Note that options don’t need to apply to the current class; they are set but the factory doesn’t change the current class in this case.

The options will be preceded by banner. If uniquify is true, the names of the options will be made as unique as possible.



85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/MetaBuilder/factory.rb', line 85

def option_parser_factory(parser, banner = "", uniquify = true)
  parser.separator banner
  # A for loop won't work here as name would be overwritten
  # for every iteration.
  @instances.each do |name, instance|
    name
    parser.on("--#{name}", instance.description.banner(instance)) do 
      self.current = name
    end
    instance.option_parser_options(parser, uniquify)
    parser.separator ""
  end
end