Skip to content

Commit

Permalink
create AttributeSequence class
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammednasser-32 committed May 13, 2024
1 parent b593ce1 commit 213bd29
Show file tree
Hide file tree
Showing 5 changed files with 30 additions and 11 deletions.
1 change: 1 addition & 0 deletions lib/factory_bot.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
require "factory_bot/decorator/new_constructor"
require "factory_bot/linter"
require "factory_bot/version"
require "factory_bot/attribute_sequence"

module FactoryBot
Deprecation = ActiveSupport::Deprecation.new("7.0", "factory_bot")
Expand Down
24 changes: 24 additions & 0 deletions lib/factory_bot/attribute_sequence.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
module FactoryBot
# @api private
class AttributeSequence
attr_reader :expression

def initialize(&block)
@expression = block
end

def evaluate(index)
expression.call(index)
end

def self.evaluate_attributes(traits_and_overrides, i)
traits_and_overrides.map do |attribute|
next attribute unless attribute.is_a?(Hash)

attribute.transform_values do |value|
value.is_a?(self) ? value.evaluate(i) : value
end
end
end
end
end
4 changes: 3 additions & 1 deletion lib/factory_bot/strategy_syntax_method_registrar.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ def define_list_strategy_method

Array.new(amount) do |i|
block_with_index = StrategySyntaxMethodRegistrar.with_index(block, i)
send(strategy_name, name, *evaluate_sequence_attributes(traits_and_overrides, i), &block_with_index)
traits_and_evaluated_overrides =
FactoryBot::AttributeSequence.evaluate_attributes(traits_and_overrides, i)
send(strategy_name, name, *traits_and_evaluated_overrides, &block_with_index)
end
end
end
Expand Down
10 changes: 1 addition & 9 deletions lib/factory_bot/syntax/methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,15 +131,7 @@ def generate_list(name, count)
end

def build_sequence(&block)
block
end

def evaluate_sequence_attributes(traits_and_overrides, i)
traits_and_overrides.map do |attribute|
next attribute unless attribute.is_a?(Hash)

attribute.transform_values { |value| value.respond_to?(:call) ? value.call(i) : value }
end
FactoryBot::AttributeSequence.new(&block)
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion spec/acceptance/create_list_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
end

context "with sequencial attributes" do
subject { FactoryBot.create_list(:post, 20, title: FactoryBot.build_sequence{|n| "title_#{n}"}) }
subject { FactoryBot.create_list(:post, 20, title: FactoryBot.build_sequence{ |n| "title_#{n}" }) }

it "create sequencial attribute values" do
subject.each_with_index do |record, i|
Expand Down

0 comments on commit 213bd29

Please sign in to comment.