module Mongoid::Attributes::Readonly

This module defines behavior for readonly attributes.

Public Instance Methods

attribute_writable?(name) click to toggle source

Are we able to write the attribute with the provided name?

@example Can we write the attribute?

model.attribute_writable?(:title)

@param [ String, Symbol ] name The name of the field.

@return [ true, false ] If the document is new, or if the field is not

readonly.

@since 3.0.0

# File lib/mongoid/attributes/readonly.rb, line 27
def attribute_writable?(name)
  new_record? || (!readonly_attributes.include?(name) && _loaded?(name))
end

Private Instance Methods

_loaded?(name) click to toggle source
# File lib/mongoid/attributes/readonly.rb, line 42
def _loaded?(name)
  __selected_fields.nil? || projected_field?(name)
end
as_writable_attribute!(name, value = :nil) { |normalized_name| ... } click to toggle source
# File lib/mongoid/attributes/readonly.rb, line 33
def as_writable_attribute!(name, value = :nil)
  normalized_name = database_field_name(name)
  if attribute_writable?(normalized_name)
    yield(normalized_name)
  else
    raise Errors::ReadonlyAttribute.new(name, value)
  end
end
projected_field?(name) click to toggle source
# File lib/mongoid/attributes/readonly.rb, line 46
def projected_field?(name)
  projected = (__selected_fields || {}).keys.select { |f| __selected_fields[f] == 1 }
  projected.empty? || projected.include?(name)
end