2011-10-08 23:36:38 +02:00
|
|
|
class Factory
|
|
|
|
@factories = {}
|
|
|
|
|
2011-10-26 15:46:25 +02:00
|
|
|
class << self
|
2011-10-08 23:36:38 +02:00
|
|
|
def add(name, klass, &block)
|
|
|
|
@factories[name] = [klass, block]
|
|
|
|
end
|
|
|
|
|
|
|
|
def create(name, opts = {})
|
|
|
|
new(name, opts).tap(&:save!)
|
|
|
|
end
|
|
|
|
|
2012-03-01 16:00:14 +01:00
|
|
|
def new(name, opts = {})
|
|
|
|
factory= @factories[name]
|
2011-10-08 23:36:38 +02:00
|
|
|
factory[0].new.tap do |obj|
|
2011-10-26 15:46:25 +02:00
|
|
|
factory[1].call(obj)
|
2011-10-08 23:36:38 +02:00
|
|
|
end.tap do |obj|
|
|
|
|
opts.each do |k, opt|
|
2011-10-26 15:46:25 +02:00
|
|
|
obj.send("#{k}=", opt)
|
2011-10-08 23:36:38 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def Factory(name, opts={})
|
|
|
|
Factory.create name, opts
|
|
|
|
end
|
|
|
|
|