Skip to content

Instantly share code, notes, and snippets.

@bgentry
Created October 6, 2010 05:22
Show Gist options
  • Save bgentry/612867 to your computer and use it in GitHub Desktop.
Save bgentry/612867 to your computer and use it in GitHub Desktop.
require 'dm-core'
require 'active_model'
module ActiveModel
module MassAssignmentSecurity
module Sanitizer
# Returns all attributes not denied by the authorizer.
def sanitize(attributes)
sanitized_attributes = attributes.reject do |key, value|
key_name = key.name rescue key
deny?(key_name)
end
debug_protected_attribute_removal(attributes, sanitized_attributes)
sanitized_attributes
end
end
end
end
module DataMapper
# = Active Model Mass-Assignment Security
module MassAssignmentSecurity
include ::ActiveModel::MassAssignmentSecurity
def self.included(base)
base.class_eval do
class_attribute :_accessible_attributes
class_attribute :_protected_attributes
class_attribute :_active_authorizer
end
base.extend ::ActiveModel::MassAssignmentSecurity::ClassMethods
base.extend ClassMethods
end
module ClassMethods
def logger
@logger ||= Rails.logger
end
end
def attributes=(attributes, guard_protected_attributes = true)
attributes = sanitize_for_mass_assignment(attributes) if guard_protected_attributes
super(attributes)
end
end
end
require 'dm-mass_assignment_security'
class User
include DataMapper::Resource
include DataMapper::MassAssignmentSecurity
# Alternatively, you can include MassAssignmentSecurity in every DataMapper Model/Resource with this:
# DataMapper::Model.append_inclusions(DataMapper::MassAssignmentSecurity)
# Properties
property :id, Serial
property :username, String
property :real_name, String
property :email, String
property :type, Discriminator
timestamps :at
# Mass-assignment protection
attr_accessible :username, :real_name, :email
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment