Module: Rave::Mixins::ObjectFactory
- Included in:
- Rave::Models::Annotation, Rave::Models::Element, Rave::Models::Event
- Defined in:
- lib/mixins/object_factory.rb
Overview
Abstract object that allows you to create instances of the classes inside it based on providing a type name.
Constant Summary collapse
- WILDCARD =
'*'
Instance Attribute Summary collapse
-
#type ⇒ Object
readonly
:nodoc:.
Class Method Summary collapse
Instance Attribute Details
#type ⇒ Object (readonly)
:nodoc:
81 82 83 |
# File 'lib/mixins/object_factory.rb', line 81 def type @type end |
Class Method Details
.included(base) ⇒ Object
8 9 10 11 12 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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/mixins/object_factory.rb', line 8 def self.included(base) base.class_eval do # Store the registered classes in a class instance variable. class << self attr_reader :class_by_type_mapping attr_reader :class_by_pattern_mapping end @class_by_type_mapping = {} @class_by_pattern_mapping = {} class_eval(<<-END, __FILE__, __LINE__) def self.classes_by_type ::#{self.name}.class_by_type_mapping end def self.classes_by_pattern ::#{self.name}.class_by_pattern_mapping end END # Object factory method. # # :type - Type of object to create [String] def self.create(type, *args, &block) if classes_by_type.has_key? type return classes_by_type[type].new(*args, &block) elsif # Check for pattern-based types. Check for longer matches before shorter ones. patterns = classes_by_pattern.keys.sort { |a, b| b.to_s.length <=> a.to_s.length } patterns.each do |pattern| if type =~ pattern return classes_by_pattern[pattern].new($1, *args, &block) end end raise ArgumentError.new("Unknown #{self} type #{type}") end end # Is this type able to be created? def self.valid_type?(type) classes_by_type.has_key? type end # Register this class with its factory. def self.factory_register(type) classes_by_type[type] = self # * in a type indicates a wildcard. if type[WILDCARD] classes_by_pattern[/^#{type.sub(WILDCARD, '(.*)')}$/] = self end class << self def type; @type.dup; end end @type = type end # Classes that can be generated by the factory [Array of Class] def self.classes classes_by_type.values end # Types that can be generated by the factory [Array of String] def self.types classes_by_type.keys end end end |