Skip to content

Instantly share code, notes, and snippets.

@kevinthompson
Last active December 10, 2015 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinthompson/4495967 to your computer and use it in GitHub Desktop.
Save kevinthompson/4495967 to your computer and use it in GitHub Desktop.
Convert a single FactoryGirl factory file into a directory of factories.
#!/usr/bin/env ruby
require 'fileutils'
# Set Source and Destination
source = ARGV[0] || "#{Dir.pwd}/spec/factories.rb"
destination = ARGV[1] || "#{Dir.pwd}/spec/factories/"
# Verify Source and Destination Exist
puts '! Source file does not exist.' unless File.exists?(source)
FileUtils.mkpath destination unless File.directory?(destination)
# Parse Factories
data = File.read(source)
matches = data.scan(/(([\t ]*)factory :(\w+).*?\n\2end)/m)
# Create Factory Files
puts "\n"
puts '-' * 40
puts 'Creating Factories'
puts '-' * 40
count = 0
matches.each do |match|
factory = match[0]
file = [destination,match[2],'_factory.rb'].join
next if File.exists?(file)
puts file
count += 1 if File.open(file, 'w+'){ |f| f.write("FactoryGirl.define do\n#{factory}\nend") }
end
puts '-' * 40
puts "#{count} factor#{count == 1 ? 'y' : 'ies'} created.\n\n"
# Delete Source Factory File
puts 'Delete source file? [y/n]'
File.delete(source) if gets =~ /y(es)?/i
@kevinthompson
Copy link
Author

This gist currently depends on the factory file being properly indented, as it matches a factory statement and it's associated end based on their indentation. I would, however, like to expand the parser to match the appropriate end regardless of its indentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment