Skip to content

Instantly share code, notes, and snippets.

@ilyakatz
Forked from sobrinho/factory_girl_cache.rb
Created August 20, 2012 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilyakatz/3408018 to your computer and use it in GitHub Desktop.
Save ilyakatz/3408018 to your computer and use it in GitHub Desktop.
Object caching for factory girl
module FactoryGirl
module Strategy
class Cache
def association(runner)
runner.run(:cache)
end
def result(evaluation)
r = Repository.instance.read(evaluation)
if r
puts "hit"
else
puts "miss"
r = Repository.instance.store(evaluation)
#debugger
end
r
end
end
class Repository
include Singleton
def initialize
recycle!
end
def recycle!
self.repository = Hash.new()
end
def read(evaluation)
r = repository[evaluation.object.class.to_s.to_sym]
#debugger
#r
#if r
# puts "found "
#else
# debugger
#puts "not found"
#end
end
def store(evaluation)
obj = evaluation.object.tap do |object|
evaluation.notify(:after_build, object)
evaluation.notify(:before_create, object)
evaluation.create(object)
evaluation.notify(:after_create, object)
end
repository[evaluation.object.class.to_s.to_sym] = obj
end
attr_accessor :repository
end
end
end
FactoryGirl.register_strategy(:cache, FactoryGirl::Strategy::Cache)
#RSpec.configure do |config|
# config.before(:suite) do
# FactoryGirl::Strategy::Repository.instance.recycle!
# end
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment