Sha256: 667d0c9d3a2ff0fffd24d20a3f369e70a1774e40025da811cd62ab70724b3c3e

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

# Implements the mass_assign instance and class methods. Include in your class for easy mass assignments.
#
#   class Book
#     attr_accessor :title, :author
#     include MassAssignment
#   end
#
#   book = Book.mass_assign(:title => 'The Little Red Book', :author => 'Jenny from the Block')
#   book.title #=> 'The Little Red Book'
module MassAssignment
  def self.included(klass)
    klass.extend ClassMethods
  end
  
  module ClassMethods
    # Intializes a new object and assigns the attribute hash to the appropriate
    # attribute writers using the mass_assign method on the newly created object.
    #
    # Example:
    #
    #   User.mass_assign(:username => 'Manfred', :password => 'very secret')
    #
    # Instead of:
    #
    #   user = User.new
    #   user.mass_assign(:username => 'Manfred', :password => 'very secret')
    def mass_assign(attributes)
      object = new
      object.mass_assign(attributes)
      object
    end
  end
  
  # Sends all the attributes in the attribute hash to the appropriate attribute writer.
  # This is a way to circumvent the normal attribute protection on Rails models.
  #
  # Example:
  #
  #   user.mass_assign(:username => 'Manfred', :password => 'very secret')
  #
  # Instead of:
  #
  #   user.username = 'Manfred'
  #   user.password = 'very secret'
  def mass_assign(attributes)
    assign_attributes(attributes, :without_protection => true)
  end
end

class ActiveRecord::Base
  include MassAssignment
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
attribute-permissions-1.0 lib/mass_assignment.rb