Skip to content

Instantly share code, notes, and snippets.

@ezza
Created September 25, 2024 01:16
Show Gist options
  • Save ezza/fc10b1934c1ed82c918a95c032f33e6f to your computer and use it in GitHub Desktop.
Save ezza/fc10b1934c1ed82c918a95c032f33e6f to your computer and use it in GitHub Desktop.
Split a factories.rb file into subfiles by class
require "active_support"
require 'fileutils'
def calculate_file_to_write_to(line)
parts = line.strip.split ' '
if line.include? 'class:'
fname = parts[-2].gsub(',', '')
fname.gsub! '/'
fname = ActiveSupport::Inflector.underscore fname
else
fname = parts[1].gsub(':', '').gsub(',', '')
end
fname = ActiveSupport::Inflector.pluralize fname
fname = fname + '.rb'
# pluralize!
path = 'spec/factories/'
path + fname
end
def store_line(key, text)
@data[key] ||= []
@data[key] << text
end
def create_dir(fpath)
path = fpath.split('/')[0..-2].join('/')
FileUtils.mkdir_p path
end
def write_to_files
@data.each do |key,text|
create_dir key
File.write(key, "FactoryBot.define do\n", mode: 'w')
text.each do |line|
File.write(key, line, mode: 'a')
end
File.write(key, "end\n", mode: 'a')
end
end
File.open('spec/factories.rb', "r") do |f|
@data = {}
f.each_line do |line|
if line[0..8] == ' factory'
@write_to = calculate_file_to_write_to(line)
end
if @write_to
store_line(@write_to, line)
end
end
write_to_files
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment