class FactoryBot::StrategySyntaxMethodRegistrar

@api private

Public Class Methods

new(strategy_name) click to toggle source
# File lib/factory_bot/strategy_syntax_method_registrar.rb, line 4
def initialize(strategy_name)
  @strategy_name = strategy_name
end
with_index(block, index) click to toggle source
# File lib/factory_bot/strategy_syntax_method_registrar.rb, line 14
def self.with_index(block, index)
  if block&.arity == 2
    ->(instance) { block.call(instance, index) }
  else
    block
  end
end

Public Instance Methods

define_strategy_methods() click to toggle source
# File lib/factory_bot/strategy_syntax_method_registrar.rb, line 8
def define_strategy_methods
  define_singular_strategy_method
  define_list_strategy_method
  define_pair_strategy_method
end

Private Instance Methods

define_list_strategy_method() click to toggle source
# File lib/factory_bot/strategy_syntax_method_registrar.rb, line 32
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

    Array.new(amount) do |i|
      block_with_index = StrategySyntaxMethodRegistrar.with_index(block, i)
      send(strategy_name, name, *traits_and_overrides, &block_with_index)
    end
  end
end
define_pair_strategy_method() click to toggle source
# File lib/factory_bot/strategy_syntax_method_registrar.rb, line 47
def define_pair_strategy_method
  strategy_name = @strategy_name

  define_syntax_method("#{strategy_name}_pair") do |name, *traits_and_overrides, &block|
    Array.new(2) { send(strategy_name, name, *traits_and_overrides, &block) }
  end
end
define_singular_strategy_method() click to toggle source
# File lib/factory_bot/strategy_syntax_method_registrar.rb, line 24
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
define_syntax_method(name, &block) click to toggle source
# File lib/factory_bot/strategy_syntax_method_registrar.rb, line 55
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