Skip to content

Instantly share code, notes, and snippets.

@dylanj
Created July 22, 2014 13:50
Show Gist options
  • Save dylanj/15d7c9791ae319af021c to your computer and use it in GitHub Desktop.
Save dylanj/15d7c9791ae319af021c to your computer and use it in GitHub Desktop.
Splits a shitty factories.rb with multiple factory definitions into individual files for each factory. Very brittle, please never use this.
FACTORY_DIR = 'spec/factories/'
lines = File.open(ARGV[0]).read
def write_factory(factory_name, factory_class, factory_lines)
factory_file = FACTORY_DIR + factory_name + '.rb'
outs = "FactoryGirl.define do\n"
outs += " factory :#{factory_name}"
outs += ", class: '#{factory_class}'" if factory_class != nil
outs += " do\n"
factory_lines.each do |line|
outs += "#{line}\n"
end
outs += " end\n"
outs += "end\n"
puts factory_file
if File.exists?(factory_file)
puts "ERROR: #{factory_file} already exists. skipping..."
return
end
File.open( factory_file, 'w' ) do |f|
f.write(outs)
end
end
factory_def_regex = /factory :(?<factory>\S+){1}(, class: "(?<class>\S+)")? do/
factory_name = nil
factory_class = nil
factory_lines = []
lines.each_line do |line|
if factory_name != nil
# super brittle check for end of factory.
# if the indentation is off we're hosed.
if line.rstrip == ' end'
write_factory(factory_name, factory_class, factory_lines)
factory_name = nil
factory_class = nil
factory_lines = []
next
end
factory_lines << line.rstrip
else
if matches = factory_def_regex.match(line.strip)
factory_name = matches[:factory]
factory_class = matches[:class]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment