Class: Oaken::Convert::FixturesGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/oaken/convert/fixtures_generator.rb

Instance Method Summary collapse

Instance Method Details

#convert_allObject



95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/generators/oaken/convert/fixtures_generator.rb', line 95

def convert_all
  roots = @fixtures.delete(@root_model.collection)
  @fixtures = @fixtures.values.flatten

  roots.each do |fixture|
    fixture.extract_dependents @fixtures
    create_file "db/seeds/test/#{@root_model.plural}/#{fixture.name}.rb", fixture.render.chomp
  end

  @fixtures.group_by(&:model_name).each do |model_name, fixtures|
    create_file "db/seeds/test/data/#{model_name}.rb", fixtures.map(&:render).join.chomp
  end
end

#parseObject



75
76
77
78
79
80
81
82
# File 'lib/generators/oaken/convert/fixtures_generator.rb', line 75

def parse
  @fixtures = Dir.glob("test/fixtures/**/*.yml").to_h do |path|
    model_name = path.delete_prefix("test/fixtures/").chomp(".yml")
    [model_name, YAML.unsafe_load_file(path).presence&.map { Oaken::Convert::Fixture.new(model_name, _1, _2) }]
  rescue Psych::SyntaxError
    say "Skipped #{path} due to ERB content or other YAML parsing issues.", :yellow
  end.tap(&:compact_blank!)
end

#prepareObject



69
70
71
72
73
# File 'lib/generators/oaken/convert/fixtures_generator.rb', line 69

def prepare
  @root_model = ActiveModel::Name.new(options[:root_model].constantize)
  empty_directory_with_keep_file "db/seeds/data"
  empty_directory_with_keep_file "db/seeds/test/cases"
end

#prepend_prepare_to_seedsObject



84
85
86
87
88
89
90
91
92
93
# File 'lib/generators/oaken/convert/fixtures_generator.rb', line 84

def prepend_prepare_to_seeds
  namespaces = @fixtures.keys.filter_map { _1.classify if _1.include?("/") }.uniq.sort

  code  = +"Oaken.prepare do\n"
  code << "  register #{namespaces.join(", ")}\n\n" if namespaces.any?
  code << "  seed :#{@root_model.plural}, :data\n"
  code << "end\n"

  inject_into_file "db/seeds.rb", code, before: /\A/
end