# frozen_string_literal: true # requires `ActiveModel::AttributeAssignment` and `Hash#stringify_keys` module ActiveModel module AttributeAssignment # Allows you to set nil attributes by passing in a hash of attributes with # keys matching the attribute names. # # @raise [ActiveModel::ForbiddenAttributesError] If the passed hash responds to `permitted?` method # and the return value of this method is +false+. # # @example # # class Cat # include ActiveModel::AttributeAssignment # attr_accessor :name, :status # end # # cat = Cat.new # cat.assign_nil_attributes(name: "Gorby") # cat.name # => 'Gorby' # cat.status # => nil # cat.assign_nil_attributes(status: "yawning") # cat.name # => 'Gorby' # cat.status # => 'yawning' # cat.assign_nil_attributes(status: "sleeping") # cat.name # => 'Gorby' # cat.status # => 'yawning' # # @param new_attributes # # @return [void] # def assign_nil_attributes(new_attributes) unless new_attributes.respond_to?(:stringify_keys) raise(ArgumentError, 'When assigning attributes, you must pass a hash as an argument.') end return if new_attributes.empty? attributes = new_attributes.stringify_keys _assign_nil_attributes(sanitize_for_mass_assignment(attributes)) end private # Assign any `nil` attribute # # @param attributes [Hash] # # @return [void] # def _assign_nil_attributes(attributes) attributes.each do |k, v| next unless v.nil? _assign_attribute(k, v) end end end end