Class: AgentCode::Blueprint::Generators::FactoryGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/agentcode/blueprint/generators/factory_generator.rb

Overview

Generates FactoryBot factory files with smart Faker detection. Reuses faker mapping logic from GenerateCommand.

Instance Method Summary collapse

Instance Method Details

#generate(blueprint) ⇒ String

Generate a FactoryBot factory file.

Parameters:

  • blueprint (Hash)

    ParsedBlueprint

Returns:

  • (String)

    Ruby source code



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
# File 'lib/agentcode/blueprint/generators/factory_generator.rb', line 13

def generate(blueprint)
  model_name = blueprint[:model]
  factory_name = model_name.underscore
  columns = blueprint[:columns]

  field_lines = columns.map do |col|
    next if col[:name] == "organization_id" && blueprint[:options][:belongs_to_organization]

    if col[:type] == "foreignId" || col[:type] == "references"
      if col[:foreign_model]
        relation = col[:name].sub(/_id\z/, "")
        "    association :#{relation}, factory: :#{col[:foreign_model].underscore}"
      else
        "    #{col[:name]} { Faker::Number.between(from: 1, to: 10) }"
      end
    else
      "    #{col[:name]} { #{column_to_faker(col)} }"
    end
  end.compact

  <<~RUBY
    # frozen_string_literal: true

    FactoryBot.define do
      factory :#{factory_name} do
    #{field_lines.join("\n")}
      end
    end
  RUBY
end