module DataMapper::MassAssignmentSecurity

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
# File lib/dm-rails/mass_assignment_security.rb, line 84
def attributes=(attributes, guard_protected_attributes = true)
  attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
  super(attributes)
end