Module: ActiveModel::UpdatePermittedAttributes

Defined in:
lib/modify_resource/rails/active_model/update_permitted_attributes.rb

Overview

This variable is to aid models methods that need the current user. It is very different from solutions that use Thread –

  1. First of all, it’s paired with modify_resource_with, and

  2. I’ve hooked into after_save to double-ensure that the @as_user variable is unset after any change.

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Add/override statechanging methods to ensure @as_user is unset



60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/modify_resource/rails/active_model/update_permitted_attributes.rb', line 60

def self.included(base)
  # We need ActiveModel callbacks
  base.extend ActiveModel::Callbacks
  
  # Add our stuff
  base.send :attr_accessor, :as_user
  base.extend ClassMethods
  
  [:after_save, :after_destroy].each do |m|
    base.send(m) do
      self.as_user = nil
    end
  end
end

Instance Method Details

#deep_attributes=(attributes) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/modify_resource/rails/active_model/update_permitted_attributes.rb', line 18

def deep_attributes=(attributes)
  attributes.each do |key, value|
    next unless key.to_s[m = /_attributes$/]
    nested = self.send key.gsub(m, '')
    if nested.respond_to? :each
      self.send(nested).each do |built|
        value.map { |sub_params| built.attributes = sub_params }
      end
      attributes.delete(key)
    else
      nested.attributes = value
    end
  end
  self.attributes = attributes
  save
end

#update_permitted_attributes(attributes) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/modify_resource/rails/active_model/update_permitted_attributes.rb', line 10

def update_permitted_attributes(attributes)
  if attributes.all_permitted?
    update_attributes(attributes, without_protection: true)
  else
    update_attributes(attributes)
  end
end