Created
October 5, 2019 11:13
-
-
Save keoghpe/81a9e5c73a87f6f0707bfb1c12e09fea to your computer and use it in GitHub Desktop.
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
# Run from the directory containing the app | |
# Given the app name | |
# Iterates over the models and replaces attr_accessible with strong params in the assocated controller | |
require 'active_support/inflector' | |
app_name = ARGV.first | |
models = Dir.entries("#{app_name}/app/models/").reject {|name| ['.', '..', '.gitkeep', 'permission.rb', 'user.rb'].include? name }.map {|name| name.split('.').first} | |
models.each do |model_name| | |
model_file_name = "#{app_name}/app/models/#{model_name}.rb" | |
controller_file_name = "#{app_name}/app/controllers/#{model_name.pluralize}_controller.rb" | |
model_contents = File.read(model_file_name) | |
puts "updating model #{model_file_name}" | |
params = model_contents.split("\n").grep(/attr_accessible/) | |
.map {|line| line.gsub(/attr_accessible/, '')} | |
new_model_contents = model_contents.gsub(/attr_accessible/, '# attr_accessible') | |
File.open(model_file_name, "w") {|file| file.puts new_model_contents } | |
controller_contents = File.read(controller_file_name) | |
if controller_contents.include? "params[:#{model_name}]" | |
params_method_name = "#{model_name}_params" | |
new_controller_contents = controller_contents.gsub("params[:#{model_name}]", params_method_name) | |
new_controller_contents = new_controller_contents.split("\n") | |
popped = '' | |
while popped.strip != "end" | |
popped = new_controller_contents.pop | |
end | |
puts "adding params" | |
new_controller_contents << "\n" | |
new_controller_contents << " def #{model_name}_params" | |
new_controller_contents << " params.require(:#{model_name}).permit(" | |
params.each_with_index do |param_line, index| | |
last = (index + 1 == params.length) | |
if last | |
new_controller_contents << " " + param_line + ")" | |
else | |
new_controller_contents << " " + param_line + "," | |
end | |
end | |
new_controller_contents << " end " | |
new_controller_contents << "end " | |
puts "opening file" | |
File.open(controller_file_name, "w") {|file| file.puts new_controller_contents.join("\n") } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment