summaryrefslogtreecommitdiff
path: root/spec/factory.rb
blob: 29e552b1474803e72cee701319e7c04dad990f57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Factory
  @factories = {}

  class << self 
    def add(name, klass, &block)
      @factories[name] = [klass, block]
    end

    def create(name, opts = {})
      new(name, opts).tap(&:save!)
    end

    def new(name, opts)
      factory = @factories[name]
      factory[0].new.tap do |obj|
        factory[1].call(obj) 
      end.tap do |obj|
        opts.each do |k, opt|
          obj.send("#{k}=", opt) 
        end
      end
    end
  end
end

def Factory(name, opts={})
  Factory.create name, opts
end