Sha256: bf39b93e13053e6d255b40db5e98db66032525a5034fbb17486985af42cf3953

Contents?: true

Size: 1.48 KB

Versions: 6

Compression:

Stored size: 1.48 KB

Contents

module FactoryBot
  # @api private
  class StrategySyntaxMethodRegistrar
    def initialize(strategy_name)
      @strategy_name = strategy_name
    end

    def define_strategy_methods
      define_singular_strategy_method
      define_list_strategy_method
      define_pair_strategy_method
    end

    private

    def define_singular_strategy_method
      strategy_name = @strategy_name

      define_syntax_method(strategy_name) do |name, *traits_and_overrides, &block|
        FactoryRunner.new(name, strategy_name, traits_and_overrides).run(&block)
      end
    end

    def define_list_strategy_method
      strategy_name = @strategy_name

      define_syntax_method("#{strategy_name}_list") do |name, amount, *traits_and_overrides, &block|
        unless amount.respond_to?(:times)
          raise ArgumentError, "count missing for #{strategy_name}_list"
        end

        amount.times.map { send(strategy_name, name, *traits_and_overrides, &block) }
      end
    end

    def define_pair_strategy_method
      strategy_name = @strategy_name

      define_syntax_method("#{strategy_name}_pair") do |name, *traits_and_overrides, &block|
        2.times.map { send(strategy_name, name, *traits_and_overrides, &block) }
      end
    end

    def define_syntax_method(name, &block)
      FactoryBot::Syntax::Methods.module_exec do
        if method_defined?(name) || private_method_defined?(name)
          undef_method(name)
        end

        define_method(name, &block)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
factory_bot-4.11.1 lib/factory_bot/strategy_syntax_method_registrar.rb
factory_bot-4.11.0 lib/factory_bot/strategy_syntax_method_registrar.rb
factory_bot-4.10.0 lib/factory_bot/strategy_syntax_method_registrar.rb
factory_bot-4.8.2 lib/factory_bot/strategy_syntax_method_registrar.rb
factory_bot-1.0.1.alpha lib/factory_bot/strategy_syntax_method_registrar.rb
factory_bot-1.0.0.alpha lib/factory_bot/strategy_syntax_method_registrar.rb