Module: ActiveGraph::Shared::MassAssignment

Extended by:
ActiveSupport::Concern
Included in:
Property
Defined in:
lib/active_graph/shared/mass_assignment.rb

Overview

MassAssignment allows you to bulk set and update attributes

Including MassAssignment into your model gives it a set of mass assignment methods, similar to those found in ActiveRecord.

Originally part of ActiveAttr, github.com/cgriego/active_attr

Examples:

Usage

class Person
  include ActiveGraph::Shared::MassAssignment
end

Instance Method Summary collapse

Instance Method Details

#add_undeclared_property(_, _) ⇒ Object



36
# File 'lib/active_graph/shared/mass_assignment.rb', line 36

def add_undeclared_property(_, _); end

#assign_attributes(new_attributes = nil) ⇒ Object

Mass update a model's attributes

Examples:

Assigning a hash

person.assign_attributes(:first_name => "Chris", :last_name => "Griego")
person.first_name #=> "Chris"
person.last_name #=> "Griego"

Parameters:

  • new_attributes (Hash{#to_s => Object}, #each) (defaults to: nil)

    Attributes used to populate the model



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/active_graph/shared/mass_assignment.rb', line 24

def assign_attributes(new_attributes = nil)
  return unless new_attributes.present?
  new_attributes.each do |name, value|
    writer = :"#{name}="
    if respond_to?(writer)
      send(writer, value)
    else
      add_undeclared_property(name, value)
    end
  end
end

#attributes=(new_attributes) ⇒ Object

Mass update a model's attributes

Examples:

Assigning a hash

person.attributes = { :first_name => "Chris", :last_name => "Griego" }
person.first_name #=> "Chris"
person.last_name #=> "Griego"

Parameters:

  • new_attributes (Hash{#to_s => Object}, #each)

    Attributes used to populate the model



46
47
48
# File 'lib/active_graph/shared/mass_assignment.rb', line 46

def attributes=(new_attributes)
  assign_attributes(new_attributes)
end

#initialize(attributes = nil) ⇒ Object

Initialize a model with a set of attributes

Examples:

Initializing with a hash

person = Person.new(:first_name => "Chris", :last_name => "Griego")
person.first_name #=> "Chris"
person.last_name #=> "Griego"

Parameters:

  • new_attributes (Hash{#to_s => Object}, #each)

    Attributes used to populate the model



58
59
60
61
# File 'lib/active_graph/shared/mass_assignment.rb', line 58

def initialize(attributes = nil)
  assign_attributes(attributes)
  super()
end