Created
December 3, 2017 13:56
-
-
Save netzfisch/11db0b9db4b3fbef86d126103578d347 to your computer and use it in GitHub Desktop.
Rake task helping to migrate a rails 3 app to rails 4 with 'strong_parameters' instead of 'attr_accessible'
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
# Rake task to help migrating a rails 3 app to rails 4 strong_parameters. | |
# The task generates source code for helper methods for each model class | |
# to 'permit' the attributes. | |
# The generated methods are intended as starting point to copy&paste in the | |
# controller and than edit the permitted attributs. | |
# Some common names of non-editable attributes are already filtered, | |
# like 'id', 'password' or 'created_at'. | |
# The output is written to stdout so you can pipe it into a file | |
# | |
# Dependencies: | |
# - rails-erd gem is used to access the models and attributes. | |
# | |
# Setup: | |
# - $ rails generate task strong_parameters | |
# - copy source into file lib/tasks/strong_parameters.rake | |
# - add to development group in Gemfile: | |
# gem 'rails-erd' | |
# | |
# Usage: | |
# - $ rake controller:strong_methods > tmp/strong_parameter_methods.rb | |
require "rails_erd/domain" | |
namespace :controller do | |
desc "generate strong parameter helper methods from model attributes" | |
task strong_methods: [:environment, "erd:load_models"] do | |
domain = RailsERD::Domain.generate # Discover all models that are currently loaded... | |
puts "# Strong parameters template methods. Copy&paste into your controllers and adjust." | |
puts | |
domain.entities.each do |entity| | |
puts "# #{entity.name} strong parameter helper method" | |
if entity.model | |
param_key = ActiveModel::Naming.param_key(entity.model) | |
puts "def #{param_key}_params" | |
puts " params.require(:#{param_key})." | |
param_list = entity.attributes.reject do |attribute| | |
attribute.to_s =~ /id|type|created_at|updated_at|_token$|_count$/ | |
end.map do | attribute| | |
':' + attribute.to_s | |
end | |
puts " permit(#{param_list.join(', ')})" | |
unless entity.model.nested_attributes_options.empty? | |
puts "# @TODO: check nested attributes for #{entity.model.nested_attributes_options.keys.join(', ')} " | |
end | |
puts "end" | |
puts | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment