Module: AttributeExt::SafeAttributes::ClassMethods

Defined in:
lib/attribute_ext/safe_attributes.rb

Instance Method Summary collapse

Instance Method Details

#safe_attributes(*attrs) ⇒ Object

Adds a whitelist rule that allows mass assignment for given attributes based on given optional conditions.

class User < ActiveRecord::Base
  # always mass assignable
  safe_attributes :name, :email
  # only when new record
  safe_attributes :login, :if => Proc.new { |user| user.new_record? }
  # only own password or as admin
  safe_attributes :password, :if => Proc.new { |user,role| user == role }
  safe_attributes :password, :as => :admin
end

All given conditions for one rule must be true to allow mass assignment for given attributes. Attributes can be added in more than one rule to allow alternatives (like password above).

Available Options:

:as

Attributes will be assignable if mass assignment role is equal (==) given object.

:if

Makes attributes assignable if given Proc block returns true.

:unless

Attributes cannot be mass assigned if Proc block evaluates to true.

The :if and :unless options must be Proc block that will be executed each time the mass assignment authorizer is called and they are called with current model and role as parameters.



79
80
81
82
83
84
85
86
87
# File 'lib/attribute_ext/safe_attributes.rb', line 79

def safe_attributes(*attrs)
  @safe_attributes ||= []
  if attrs.empty?
    @safe_attributes
  else
    options = attrs.last.is_a?(Hash) ? attrs.pop : {}
    @safe_attributes << [attrs, safe_attributes_opts(options)]
  end
end