Module: PatronusFati::FactoryBase

Included in:
MessageProcessor
Defined in:
lib/patronus_fati/factory_base.rb

Overview

This module provides the basis for an automatic Factory registration and generation system. Other modules that wish to make use of this functionality should extend this module. Those modules should then in turn be included by their respective generators.

Instance Method Summary collapse

Instance Method Details

#class_to_name(klass) ⇒ Symbol

Turns the name of a class into it’s snake cased equivalent.

Parameters:

  • klass (Object)

Returns:

  • (Symbol)


11
12
13
14
# File 'lib/patronus_fati/factory_base.rb', line 11

def class_to_name(klass)
  klass.to_s.split('::').last.scan(/[A-Z][a-z]*/).map(&:downcase)
    .join('_').to_sym
end

#factory(type, opts = {}) ⇒ void

Factory method for triggering the lookup and return of the specific requested type of factory.

Parameters:

  • type (Symbol)

    Type of generator to create

  • opts (Hash<Symbol=>String>) (defaults to: {})


21
22
23
24
25
26
27
28
# File 'lib/patronus_fati/factory_base.rb', line 21

def factory(type, opts = {})
  return if ignored_types.include?(type)
  if registered_factories[type].nil?
    PatronusFati.logger.warn("Unknown factory #{type} (Available: #{registered_factories.keys})")
    return
  end
  registered_factories[type].process(opts)
end

#ignored_typesArray<Symbol>

Placeholder mechanism to allow sub-generators to not generate any warnings for specific types.

Returns:

  • (Array<Symbol>)


34
35
36
# File 'lib/patronus_fati/factory_base.rb', line 34

def ignored_types
  []
end

#included(klass) ⇒ Object

Trigger for when this module gets included to register it with the factory.

Parameters:

  • klass (Object#create)

Returns:

  • (Object)


43
44
45
# File 'lib/patronus_fati/factory_base.rb', line 43

def included(klass)
  registered_factories[class_to_name(klass)] = klass
end

#registered_factoriesHash<Symbol=>Object>

Returns the hash containing the set of registered factories or initializes it if one doesn’t exist.

Returns:

  • (Hash<Symbol=>Object>)


51
52
53
# File 'lib/patronus_fati/factory_base.rb', line 51

def registered_factories
  @registered_factories ||= {}
end