Skip to content

Instantly share code, notes, and snippets.

@handylearn
Last active December 3, 2017 13:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save handylearn/70ad01a34e3d9f97e0b8 to your computer and use it in GitHub Desktop.
Save handylearn/70ad01a34e3d9f97e0b8 to your computer and use it in GitHub Desktop.
# 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