Created
June 15, 2017 10:52
-
-
Save mrsimo/8b75e5e82901067fb45da36282350990 to your computer and use it in GitHub Desktop.
Convert all those controller tests to the new Rails 5 syntax
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
require 'parser/current' | |
require 'byebug' | |
class FixGets < Parser::Rewriter | |
def on_send(node) | |
receiver_node, method_name, *args = *node | |
if [:get, :patch, :post, :put, :delete, :mobile_get].include?(method_name) | |
if args.size > 1 && !args[1].loc.expression.source.include?("xhr: true") | |
rub = args[1].loc.expression.source | |
is_method = args[1].to_s.start_with?("(send") | |
is_var = args[1].to_s.start_with?("(lvar") | |
is_ivar = args[1].to_s.start_with?("(ivar") | |
is_const = args[1].to_s.start_with?("(const") | |
is_hash_with_brackets = rub.strip.start_with?("{") && rub.strip.end_with?("}") | |
if is_method || is_var || is_ivar || is_const || is_hash_with_brackets | |
new_syntax = "params: #{rub}" | |
else | |
new_syntax = "params: { #{rub} }" | |
end | |
replace(args[1].loc.expression, new_syntax) | |
end | |
end | |
end | |
end | |
ARGV.each do |file| | |
if File.exists?(file) | |
code = File.read(file) | |
buffer = Parser::Source::Buffer.new('(example)') | |
buffer.source = code | |
parser = Parser::CurrentRuby.new | |
ast = parser.parse(buffer) | |
rewriter = FixGets.new | |
rewriter.rewrite(buffer, ast) | |
# Rewrite the AST, returns a String with the new form. | |
File.open(file, "w") { |f| f.write(rewriter.rewrite(buffer, ast)) } | |
else | |
puts "Skipping `#{file}`, not a file" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment