Sha256: f6cd00947f8e07470bc542b6019d143087571ceeeeef9bee5eb89efe42f7a875

Contents?: true

Size: 1.66 KB

Versions: 3

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

module FactoryBot
  module Preload
    module Helpers
      include ::FactoryBot::Syntax::Methods

      def self.load_models
        return unless defined?(Rails)

        Dir[Rails.application.root.join("app/models/**/*.rb")].each do |file|
          require_dependency file
        end
      end

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

          define_method(method_name) do |name|
            factory(name, model)
          end
        end
      end

      def self.included(_base)
        FactoryBot::Preload::Helpers.define_helper_methods
      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]

        if factory.blank? && Preload.factories[model.name].key?(name)
          factory = model.find(Preload.record_ids[model.name][name])
          Preload.factories[model.name][name] = factory
        end

        unless factory
          raise "Couldn't find #{name.inspect} factory for #{model.name.inspect} model"
        end

        factory
      end

      private def factory_set(name, &block)
        record = instance_eval(&block)
        Preload.factories[record.class.name] ||= {}
        Preload.factories[record.class.name][name.to_sym] = record

        Preload.record_ids[record.class.name] ||= {}
        Preload.record_ids[record.class.name][name.to_sym] = record.id
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
factory_bot-preload-0.2.2 lib/factory_bot/preload/helpers.rb
factory_bot-preload-0.2.1 lib/factory_bot/preload/helpers.rb
factory_bot-preload-0.2.0 lib/factory_bot/preload/helpers.rb