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
# 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: | |
# gem rails-erd is used to access the models and attributes. | |
# | |
# | |
# Installation: | |
# copy source file to ./lib/tasks | |
# add this line to Gemfile in the development group: | |
# 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