Last active
December 10, 2015 21:38
-
-
Save kevinthompson/4495967 to your computer and use it in GitHub Desktop.
Convert a single FactoryGirl factory file into a directory of factories.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This gist currently depends on the factory file being properly indented, as it matches a
factory
statement and it's associatedend
based on their indentation. I would, however, like to expand the parser to match the appropriateend
regardless of its indentation.