Created
October 30, 2009 18:11
-
-
Save ono/222597 to your computer and use it in GitHub Desktop.
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
namespace :security do | |
# ==== | |
# Usage: | |
# rake security:add_attr_accessible => edit all models which are not called either attr_accessible or attr_protected. | |
# rake security:att_attr_accessible models="blog,article" => update only blog and article. it doesn't check whether there are attr_accessible or attr_protected. | |
desc "defines attr_accessible listing all attributes but associations into model(s)" | |
task :add_attr_accessible => :environment do | |
models = ENV["models"] | |
if models.to_s.size==0 | |
models = risky_models | |
else | |
models = models.split(",").map do |model| | |
{:file=>Dir.glob("#{RAILS_ROOT}/app/models/**/#{model}.rb")[0], :class_name=>model.camelize, :class=>model.camelize.constantize} | |
end | |
end | |
models.each do |model| | |
src = File.read model[:file] | |
attributes = model[:class].attribute_names.select{|a| a!="id"}.map{|a| ":#{a}"}.join(",") | |
dst = src.sub(/(( *)class +#{model[:class_name]}[^\n]*\n)/m) {|s| "#{$1}#{$2} attr_accessible #{attributes}\n"} | |
File.open(model[:file],'w') { |f| f.write dst } | |
p "updated #{model[:file]}" | |
end | |
end | |
def risky_models | |
models = [] | |
Dir.glob("#{RAILS_ROOT}/app/models/**/*.rb") do |filename| | |
begin | |
class_name = File.basename(filename, ".rb").camelize | |
klass = class_name.constantize | |
next if klass.attr_accessible.size>0 || klass.attr_protected.size>0 # already defined | |
next if klass.attribute_names.size<=0 # hey, your are not active record, are you? | |
models << {:file=>filename, :class=>klass, :class_name=>class_name} | |
rescue=>e | |
# ignore the class. presumably it is not an ActiveRecord class. | |
#pp e | |
end | |
end | |
models | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment