Created
June 11, 2009 15:52
-
-
Save tomlea/128003 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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