Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Created March 1, 2024 00:41
Show Gist options
  • Save bradgessler/be76fa27886a1cc393833ee4a7cf909d to your computer and use it in GitHub Desktop.
Save bradgessler/be76fa27886a1cc393833ee4a7cf909d to your computer and use it in GitHub Desktop.
Rename symbols and objects in a Rails project
#!/usr/bin/env ruby
require 'fileutils'
require "active_support/all"
# Check for arguments
unless ARGV.length == 2
puts "Usage: #{$PROGRAM_NAME} <original_class_name> <new_class_name>"
exit
end
original_class_name, new_class_name = ARGV
original_underscore = original_class_name.underscore
new_underscore = new_class_name.underscore
# Define a recursive method to rename files and update file contents
def process_files(path, original_class_name, new_class_name, original_underscore, new_underscore)
Dir.foreach(path) do |item|
next if item == '.' or item == '..'
full_path = File.join(path, item)
if File.directory?(full_path)
process_files(full_path, original_class_name, new_class_name, original_underscore, new_underscore)
elsif item.end_with?('.rb')
# Rename file if necessary
if item.include?(original_underscore)
new_file_name = item.gsub(original_underscore, new_underscore)
new_full_path = File.join(path, new_file_name)
FileUtils.mv(full_path, new_full_path)
puts "Renamed #{full_path} to #{new_full_path}"
full_path = new_full_path # Update full_path to reflect the new file name for content update
end
# Update contents of the file
text = File.read(full_path)
new_text = text.gsub(original_class_name, new_class_name)
.gsub(original_underscore, new_underscore)
if text != new_text
File.open(full_path, "w") { |file| file.puts new_text }
puts "Updated references in #{full_path}"
end
end
end
end
# Start processing from the current directory
process_files(Dir.pwd, original_class_name, new_class_name, original_underscore, new_underscore)
puts "Process complete. Please manually check your application for any missed references."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment