Skip to content

Instantly share code, notes, and snippets.

@leh
Created September 1, 2011 08:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leh/1185749 to your computer and use it in GitHub Desktop.
Save leh/1185749 to your computer and use it in GitHub Desktop.
Makes attr_accessible whiny. A monkey patch for Rails 3.1 to raise an exception instead of a warning in the logs when protected fields are mass assigned
# Rails edge includes pluggable sanitizers for mass assignment. Really cool is the
# StrictSanitizer which raises an exception instead of a log message, which makes
# problems easier to spot in development.
# For the time being, there seems to be no way to achieve this in Rails 3.1 via
# configuration. Monkey patching to the rescue!
# Copy the gist into config/initializers and configure the environments in which the
# exception gets raised.
if ['development', 'test'].include?(Rails.env)
ActiveModel::MassAssignmentSecurity::BlackList.class_eval do
protected
def debug_protected_attribute_removal(attributes, sanitized_attributes)
removed_keys = attributes.keys - sanitized_attributes.keys
raise ActiveModel::MassAssignmentSecurity::Error, "Can't mass-assign protected attributes: #{removed_keys.join(', ')}" if removed_keys.any?
super(attributes, sanitized_attributes)
end
end
ActiveModel::MassAssignmentSecurity::WhiteList.class_eval do
protected
def debug_protected_attribute_removal(attributes, sanitized_attributes)
removed_keys = attributes.keys - sanitized_attributes.keys
raise ActiveModel::MassAssignmentSecurity::Error, "Can't mass-assign protected attributes: #{removed_keys.join(', ')}" if removed_keys.any?
super(attributes, sanitized_attributes)
end
end
end
class ActiveModel::MassAssignmentSecurity::Error < StandardError
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment