Sha256: fdcb6a4c0c30a810d05402cdbbf7f0fcd0a08e5cbefe7989a176597489520e44
Contents?: true
Size: 1.66 KB
Versions: 20
Compression:
Stored size: 1.66 KB
Contents
# 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
Version data entries
20 entries across 20 versions & 1 rubygems