Class: Originals::Factory

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeFactory

Returns a new instance of Factory.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/originals.rb', line 29

def initialize
    @generators = []

    Pixelart::Image.subclasses.each do |klass|
      ## check if class has self.generate method
      ##   and  NAMES constant
      has_generate = klass.respond_to?( :generate )
      ## note: defined? returns nil or name as string
      ##   use !! "hack" to turn into true/false boolean
      has_names = !!defined?( klass::NAMES )

      if has_generate && has_names
        # puts
        # puts "==> #{klass.name}"
        # pp klass::NAMES

        @generators << klass
      end
   end

   @generators_by_name = _build_generators_by_name( @generators )
end

Class Method Details

.normalize_key(str) ⇒ Object

helpers



86
87
88
# File 'lib/originals.rb', line 86

def self.normalize_key( str )    ## allow/enable easy "external" reuse - why? why not?
   str.downcase.gsub( /[ ()_-]/, '' )
end

Instance Method Details

#_build_generators_by_name(generators) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/originals.rb', line 92

def _build_generators_by_name( generators )
  h = {}

  generators.each do |klass|
     names = klass::NAMES
     names.each do |name|
        key = _normalize_key( name )

        if h[ key ]
           puts "!!! ERROR - image generator key >#{key}< for name >#{name}< is NOT unique:"
           pp klass
           puts "duplicate:"
           pp h[key]
           exit 1
        end
        h[ key ] = klass
      end
  end
  ## pp h
  h
end

#_normalize_key(str) ⇒ Object



89
# File 'lib/originals.rb', line 89

def _normalize_key( str ) self.class.normalize_key( str ); end

#can_fabricate?(name) ⇒ Boolean Also known as: can_fab?

Returns:

  • (Boolean)


63
64
65
66
# File 'lib/originals.rb', line 63

def can_fabricate?( name )
   key = _normalize_key( name )
   @generators_by_name[ key ] ? true : false
end

#fabricate(name, *attributes) ⇒ Object Also known as: fab



70
71
72
73
74
75
76
77
78
79
# File 'lib/originals.rb', line 70

def fabricate( name, *attributes )
  key = _normalize_key( name )
  klass = @generators_by_name[ key ]
  if klass
     attributes = klass::DEFAULT_ATTRIBUTES  if attributes.size == 0 && defined?( klass::DEFAULT_ATTRIBUTES )
     klass.generate( *attributes )
  else
    nil
  end
end

#listObject Also known as: ls



53
54
55
56
57
58
59
# File 'lib/originals.rb', line 53

def list
   puts
   puts "#{@generators.size} image generator(s) found:"
   @generators.each_with_index do |klass,i|
     puts "  [#{i+1}] #{klass.name} => #{klass::NAMES.join( ' | ')}"
   end
end