Class: FactorySeeder::SeedGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/factory_seeder/seed_generator.rb

Instance Method Summary collapse

Constructor Details

#initializeSeedGenerator

Returns a new instance of SeedGenerator.



5
6
7
8
# File 'lib/factory_seeder/seed_generator.rb', line 5

def initialize
  @generated_records = []
  @defined_seeds = {}
end

Instance Method Details

#define_seed(name, &block) ⇒ Object



147
148
149
# File 'lib/factory_seeder/seed_generator.rb', line 147

def define_seed(name, &block)
  @defined_seeds[name.to_sym] = block
end

#generate(factory_name, count = 1, traits = [], attributes = {}, strategy = 'create') ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/factory_seeder/seed_generator.rb', line 56

def generate(factory_name, count = 1, traits = [], attributes = {}, strategy = 'create')
  traits = traits.map(&:to_sym)
  filtered_attributes = filter_association_attributes(factory_name, attributes)

  FactorySeeder.clear_execution_logs!
  FactorySeeder.log_info("Starting #{factory_name} generation", count: count, traits: traits, strategy: strategy)

  generated_count = 0
  errors = []

  count.times do |i|
    begin
      if strategy == 'create'
        record = FactoryBot.create(factory_name, *traits, filtered_attributes)
      else
        record = FactoryBot.build(factory_name, *traits, filtered_attributes)
        record.save! if record.respond_to?(:save!)
      end
    rescue NoMethodError => e
      # Check if this is the specific error about calling a method on CollectionProxy
      raise unless e.message.include?('CollectionProxy') && e.message.include?('undefined method')

      method_name = e.message.match(/undefined method `(\w+)'/)&.[](1)
      # Try to identify which attribute might be causing the issue
      problematic_attrs = attributes.select { |k, v| v.to_s == method_name || k.to_s == method_name }
      if problematic_attrs.any?
        raise NoMethodError,
              "#{e.message}. This might be caused by passing '#{problematic_attrs.keys.first}' as an attribute. Collection associations (has_many, has_and_belongs_to_many) cannot be set directly via attributes."
      else
        raise NoMethodError,
              "#{e.message}. This might be caused by an attribute that matches an association name. Try removing association-related attributes from your attributes hash."
      end
    end

    @generated_records << {
      factory: factory_name,
      record: record,
      traits: traits,
      attributes: attributes,
      strategy: strategy
    }

    generated_count += 1

    FactorySeeder.log("āœ… Generated #{factory_name} ##{i + 1}", level: :success)
    puts "āœ… Generated #{factory_name} ##{i + 1}" if FactorySeeder.configuration.verbose
  rescue StandardError => e
    error_msg = "Failed to generate #{factory_name} ##{i + 1}: #{e.message}"
    errors << error_msg
    FactorySeeder.log(error_msg, level: :error)
    puts "āŒ #{error_msg}" if FactorySeeder.configuration.verbose
  end

  FactorySeeder.log_info('Completed generation', generated_count: generated_count, errors: errors.count)
  logs = FactorySeeder.normalized_logs(FactorySeeder.execution_logs)
  FactorySeeder.clear_execution_logs!

  {
    factory: factory_name,
    generated_records: @generated_records,
    count: generated_count,
    requested_count: count,
    traits: traits,
    attributes: attributes,
    strategy: strategy,
    errors: errors,
    logs: logs
  }
end

#has_seed?(name) ⇒ Boolean

Returns:

  • (Boolean)


164
165
166
# File 'lib/factory_seeder/seed_generator.rb', line 164

def has_seed?(name)
  @defined_seeds.key?(name.to_sym)
end

#list_seedsObject



160
161
162
# File 'lib/factory_seeder/seed_generator.rb', line 160

def list_seeds
  @defined_seeds.keys
end

#preview(factory_name, count = 1, traits = [], attributes = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/factory_seeder/seed_generator.rb', line 10

def preview(factory_name, count = 1, traits = [], attributes = {})
  traits = traits.map(&:to_sym)
  filtered_attributes = filter_association_attributes(factory_name, attributes)

  preview_data = []
  count.times do |i|
    begin
      # Build without saving
      record = FactoryBot.build(factory_name, *traits, filtered_attributes)
    rescue NoMethodError => e
      # Check if this is the specific error about calling a method on CollectionProxy
      raise unless e.message.include?('CollectionProxy') && e.message.include?('undefined method')

      method_name = e.message.match(/undefined method `(\w+)'/)&.[](1)
      # Try to identify which attribute might be causing the issue
      problematic_attrs = attributes.select { |k, v| v.to_s == method_name || k.to_s == method_name }
      if problematic_attrs.any?
        raise NoMethodError,
              "#{e.message}. This might be caused by passing '#{problematic_attrs.keys.first}' as an attribute. Collection associations (has_many, has_and_belongs_to_many) cannot be set directly via attributes."
      else
        raise NoMethodError,
              "#{e.message}. This might be caused by an attribute that matches an association name. Try removing association-related attributes from your attributes hash."
      end
    end

    preview_data << {
      index: i + 1,
      attributes: record.attributes,
      associations: extract_associations(record)
    }
  rescue StandardError => e
    preview_data << {
      index: i + 1,
      error: e.message
    }
  end

  {
    factory: factory_name,
    count: count,
    traits: traits,
    attributes: attributes,
    preview: preview_data
  }
end

#run_all_seedsObject



168
169
170
171
172
173
174
175
# File 'lib/factory_seeder/seed_generator.rb', line 168

def run_all_seeds
  puts '🌱 Running all defined seeds...'
  @defined_seeds.each do |name, block|
    puts "\n--- Running seed: #{name} ---"
    block.call(self)
  end
  puts "\nāœ… All seeds completed successfully"
end

#run_seed(name) ⇒ Object



151
152
153
154
155
156
157
158
# File 'lib/factory_seeder/seed_generator.rb', line 151

def run_seed(name)
  seed_name = name.to_sym
  unless @defined_seeds.key?(seed_name)
    raise "Seed '#{name}' not found. Available seeds: #{@defined_seeds.keys.join(', ')}"
  end

  @defined_seeds[seed_name].call(self)
end

#summaryObject



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/factory_seeder/seed_generator.rb', line 126

def summary
  return 'No records generated' if @generated_records.empty?

  summary = "šŸ“Š Generation Summary:\n"
  summary += "#{'=' * 50}\n"

  by_factory = @generated_records.group_by { |r| r[:factory] }

  by_factory.each do |factory_name, records|
    summary += "\nšŸ­ #{factory_name}: #{records.count} records\n"
    records.each_with_index do |record, index|
      summary += "   #{index + 1}. Strategy: #{record[:strategy]}"
      summary += ", Traits: #{record[:traits].join(', ')}" if record[:traits].any?
      summary += ", Attributes: #{record[:attributes]}" if record[:attributes].any?
      summary += "\n"
    end
  end

  summary
end