-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This script is really a one time script for searching for files that use `FactoryBot.build` or `FactoryBot.create`, and replace them with the straight `ActiveRecord` equivalents.
- Loading branch information
1 parent
7b3caef
commit 21317d4
Showing
1 changed file
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
#!/usr/bin/env ruby | ||
|
||
require 'optparse' | ||
|
||
opts ={ | ||
:dirs => ['spec'], | ||
:class => nil | ||
} | ||
|
||
parser = OptionParser.new do |opt| | ||
opt.banner = "Usage: #{File.basename $0} [options] factory" | ||
|
||
opt.separator "" | ||
opt.separator "Scans the list of directories (default: 'spec/') for usages" | ||
opt.separator "of `FactoryBot.create` or `FactoryBot.build` of the given" | ||
opt.separator "factory, and replaces the contents of the file with a direct" | ||
opt.separator "ActiveRecord call." | ||
opt.separator "" | ||
opt.separator "An optional --class can be passed, which will inform the" | ||
opt.separator "script of the the replacements class should be, otherwise" | ||
opt.separator "that is derived from the factory name" | ||
opt.separator "" | ||
opt.separator "Options" | ||
|
||
opt.on("-c", "--class=CLASS", String, "class to replace factory with") do |klass| | ||
opts[:class] = klass | ||
end | ||
|
||
opt.on("-d", "--dirs=DIRS", Array, "directories to search (default: spec)") do |dirs| | ||
opts[:dirs] = dirs | ||
end | ||
end.parse! | ||
|
||
factory = ARGV.shift | ||
unless factory | ||
puts parser.help + "\n\n" | ||
raise "Missing factory to replace!" | ||
end | ||
|
||
regexp = Regexp.new "FactoryBot.(create|build)\\(:#{factory}(, ?|\\))" | ||
dirs = opts[:dirs].join(' ') | ||
cmd = %Q`grep -lER "#{regexp.source}" #{dirs}` | ||
files = `#{cmd}` | ||
|
||
if files | ||
klass = opts[:class] | ||
klass ||= factory.tr(':', '') | ||
.split('_') | ||
.map(&:capitalize) | ||
.join | ||
|
||
files.lines.map!(&:chomp).each do |file| | ||
puts "replacing contents for '#{file}'..." | ||
|
||
contents = File.read file | ||
|
||
contents.gsub!(regexp) do |match| | ||
result = "#{klass}.#{$1}" | ||
result += "(" if $2 != ")" | ||
result | ||
end | ||
File.write file, contents | ||
end | ||
else | ||
puts "no factories found with #{factory} factories" | ||
end |