Skip to content

Instantly share code, notes, and snippets.

@tomlea
Created June 11, 2009 15:52
Show Gist options
  • Save tomlea/128003 to your computer and use it in GitHub Desktop.
Save tomlea/128003 to your computer and use it in GitHub Desktop.
# Example Usage:
#
# FactoryWithCallbacks.define :product do |p|
# p.on_create do |prod|
# Factory(:product_alias, :product => prod)
# end
# end
class FactoryWithCallbacks < Factory
def initialize(*args)
super
@callbacks = Hash.new {|h, v| h[v] = [] }
end
def self.define(name, options = {})
instance = new(name, options)
yield(instance)
if parent = options.delete(:parent)
instance.inherit_from(factory_by_name(parent))
end
factories[instance.factory_name] = instance
end
def self.factories
superclass.factories
end
def run(proxy_class, overrides) #:nodoc:
ob = super
@callbacks[proxy_class].each do |callback|
callback.call(ob)
end
ob
end
def on_create(&block)
@callbacks[Proxy::Create] << block
end
def on_stub(&block)
@callbacks[Proxy::Stub] << block
end
def on_build(&block)
@callbacks[Proxy::Build] << block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment