Module: SudoAttributes::ClassMethods

Defined in:
lib/sudo_attributes.rb

Instance Method Summary collapse

Instance Method Details

#sudo_create(attributes = nil, &block) ⇒ Object

Creates an object (or multiple objects) with protected attributes and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

The attributes parameter can be either be a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.

Examples

# Create a single new object
User.sudo_create(:first_name => 'Pete')

# Create an Array of new objects
User.sudo_create([{ :first_name => 'Pete' }, { :first_name => 'Sebastian' }])

# Create a single object and pass it into a block to set other attributes.
User.sudo_create(:first_name => 'Pete') do |u|
  u.is_admin = false
end

# Creating an Array of new objects using a block, where the block is executed for each object:
User.sudo_create([{ :first_name => 'Pete' }, { :first_name => 'Sebastian' }]) do |u|
  u.is_admin = false
end


25
26
27
28
29
30
31
32
33
34
# File 'lib/sudo_attributes.rb', line 25

def sudo_create(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| sudo_create(attr, &block) }
  else
    object = sudo_new(attributes)
    yield(object) if block_given?
    object.save
    object
  end
end

#sudo_create!(attributes = nil, &block) ⇒ Object

Creates an object just like sudo_create but calls save! instead of save so an exception is raised if the record is invalid

Example

# Create a single new object where admin is a protected attribute
User.sudo_create!(:first_name => 'Pete', :admin => true)


41
42
43
44
45
46
47
48
49
50
# File 'lib/sudo_attributes.rb', line 41

def sudo_create!(attributes = nil, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| sudo_create!(attr, &block) }
  else
    object = sudo_new(attributes)
    yield(object) if block_given?
    object.save!
    object
  end
end

#sudo_new(attributes = nil) ⇒ Object Also known as: sudo_build

Instantiates an object just like ActiveRecord::Base.new, but allowing mass assignment of protected attributes

Example

# Instantiate an object where admin is a protected attribute
User.sudo_new(:first_name => 'Pete', :admin => true)


57
58
59
60
61
# File 'lib/sudo_attributes.rb', line 57

def sudo_new(attributes = nil)
  instance = new(nil)
  instance.sudo_assign_attributes(attributes)
  instance
end