Sha256: 140f06bd624ab05112c47d4a7f831184e676b620f7a76a4c40260135c172059c

Contents?: true

Size: 1.2 KB

Versions: 4

Compression:

Stored size: 1.2 KB

Contents

module Factory
  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

        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 = 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 factory_set(name, &block)
        record = block.call
        Factory::Preload.factories[record.class.name] ||= {}
        Factory::Preload.factories[record.class.name][name.to_sym] = record
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
factory_girl-preload-1.0.2 lib/factory_girl/preload/helpers.rb
factory_girl-preload-1.0.1 lib/factory_girl/preload/helpers.rb
factory_girl-preload-1.0.0 lib/factory_girl/preload/helpers.rb
factory_girl-preload-1.0.0.rc1 lib/factory_girl/preload/helpers.rb