module DataMapper::MassAssignmentSecurity

In rails ~> 4.0, protected_attributes must be required to use this feature. By requiring it here, we avoid gem load order problems that would cause the module to not exist if protected attributes was loaded after dm-rails.

Also this dummy module is inserted to avoid throwing a useless error when the module would otherwise not exist. This is less mysterious than some part of the DataMapper code just going missing because you didn’t add protected_attributes to your Gemfile.

Include this module into a DataMapper model to enable ActiveModel’s mass assignment security.

To use second parameter of {#attributes=} make sure to include this module last.

Public Instance Methods

attributes=(attributes, guard_protected_attributes = true) click to toggle source

Sanitizes the specified attributes according to the defined mass-assignment security rules and calls super with the result.

Use either attr_accessible to specify which attributes are allowed to be assigned via {#attributes=}, or attr_protected to specify which attributes are not allowed to be assigned via {#attributes=}.

attr_accessible and attr_protected are mutually exclusive.

@param [Hash{Symbol,String,::DataMapper::Property,::DataMapper::Relationship=>Object}] attributes

Names and values of attributes to sanitize.

@param [Boolean] guard_protected_attributes

Determines whether mass-security rules are applied (when +true+) or not.

@return [Hash]

Sanitized hash of attributes.

@api public

@example [Usage]

class User
  include DataMapper::Resource
  include DataMapper::MassAssignmentSecurity

  property :name, String
  property :is_admin, Boolean

  # Only allow name to be set via #attributes=
  attr_accessible :name
end

user = User.new
user.attributes = { :username => 'Phusion', :is_admin => true }
user.username  # => "Phusion"
user.is_admin  # => false

user.send(:attributes=, { :username => 'Phusion', :is_admin => true }, false)
user.is_admin  # => true
Calls superclass method
# File lib/dm-rails/mass_assignment_security.rb, line 111
def attributes=(attributes, guard_protected_attributes = true)
  attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
  super(attributes)
end