Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 762b66c32b
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 51 lines (43 sloc) 1.326 kb
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
module FactoryGirl
  module Preload
    module Helpers
      def self.extended(base)
        included(base)
      end

      def self.included(base)
        Dir[Rails.application.root.join("app/models/**/*.rb")].each do |file|
          require_dependency file
        end if defined?(Rails)

        ActiveRecord::Base.descendants.each do |model|
          method_name = model.name.underscore.gsub("/", "_").pluralize

          class_eval <<-RUBY, __FILE__, __LINE__
def #{method_name}(name)
factory(name, ::#{model})
end
RUBY
        end
      end

      def factory(name, model = nil, &block)
        if block_given?
          factory_set(name, &block)
        else
          factory_get(name, model)
        end
      end

      private
      def factory_get(name, model)
        factory = Preload.factories[model.name][name] rescue nil
        raise "Couldn't find #{name.inspect} factory for #{model.name.inspect} model" unless factory
        factory
      end

      def create(name, attrs = {})
        FactoryGirl.create(name, attrs)
      end

      def factory_set(name, &block)
        record = instance_eval(&block)
        Preload.factories[record.class.name] ||= {}
        Preload.factories[record.class.name][name.to_sym] = record
      end
    end
  end
end
Something went wrong with that request. Please try again.