Class: SeedBuilder::Loader

Inherits:
Object
  • Object
show all
Defined in:
lib/seed_builder/loader.rb

Instance Method Summary collapse

Instance Method Details

#load_seedObject



3
4
5
6
7
8
9
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
# File 'lib/seed_builder/loader.rb', line 3

def load_seed
  prepare_active_record

  default_seeds_rb = SeedBuilder.config.default_seeds_full_path
  if File.exist?(default_seeds_rb) && SeedBuilder.config.load_default_seeds?
    started_at = Time.current
    logger.tagged("seed") do
      logger.info "== #{SeedBuilder.config.default_seeds_path}: seeding"
    end
    load default_seeds_rb
    logger.tagged("seed") do
      logger.info "== #{SeedBuilder.config.default_seeds_path}: seeded (#{(Time.current - started_at).round(4)}s)"
    end
  end

  base_path = SeedBuilder.config.seeds_full_path
  if File.exist?(base_path) && SeedBuilder.config.load_seeds?
    Dir[SeedBuilder.config.seeds_path_glob]
      .map { |f| File.basename(f, ".*") }
      .each do |seed_path|
        load "#{base_path}/#{seed_path}.rb"
        timestamp, klass_name = seed_path.scan(/^([0-9]+)_(.+)$/).first
        next if klass_name.blank?

        execute_seed_class(klass_name, timestamp)
      end
  else
    logger.tagged("seed") do
      logger.warn "Seed directory #{base_path} does not exist"
    end
  end
end

#load_seed_file(seed_name) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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
# File 'lib/seed_builder/loader.rb', line 36

def load_seed_file(seed_name)
  prepare_active_record

  base_path = SeedBuilder.config.seeds_full_path
  unless File.exist?(base_path)
    logger.tagged("seed") do
      logger.warn "Seed directory #{base_path} does not exist"
    end
    return
  end

  # Find the seed file by name
  # Supports: "create_users", "20241206200111_create_users", "20241206200111"
  result = find_seed_file(base_path, seed_name)

  if result.nil?
    logger.tagged("seed") do
      logger.warn "Seed file '#{seed_name}' not found in #{base_path}"
    end
    return
  elsif result == :ambiguous
    matches = find_seed_file_matches(base_path, seed_name)
    logger.tagged("seed") do
      logger.warn "Multiple seed files match '#{seed_name}':"
      matches.each do |file|
        logger.warn "  - #{File.basename(file, ".*")}"
      end
      logger.warn "Please be more specific using the full name with timestamp (e.g., 20241206200111_create_users)"
    end
    return
  end

  seed_file = result

  seed_path = File.basename(seed_file, ".*")
  timestamp, klass_name = seed_path.scan(/^([0-9]+)_(.+)$/).first

  if klass_name.blank?
    logger.tagged("seed") do
      logger.warn "Invalid seed file format: #{seed_path}. Expected format: TIMESTAMP_CLASS_NAME.rb"
    end
    return
  end

  load seed_file
  execute_seed_class(klass_name, timestamp, seed_name)
end