module Mongoid::Traversable::DiscriminatorAssignment

Module used for prepending to the various discriminator_*= methods

@api private

Public Instance Methods

discriminator_key=(value) click to toggle source
Calls superclass method
# File lib/mongoid/traversable.rb, line 26
def discriminator_key=(value)
  if hereditary?
    raise Errors::InvalidDiscriminatorKeyTarget.new(self, self.superclass)
  end

  _mongoid_clear_types

  if value
    Mongoid::Fields::Validators::Macro.validate_field_name(self, value)
    value = value.to_s
    super
  else
    # When discriminator key is set to nil, replace the class's definition
    # of the discriminator key reader (provided by class_attribute earlier)
    # and re-delegate to Mongoid.
    class << self
      delegate :discriminator_key, to: ::Mongoid
    end
  end

  # This condition checks if the new discriminator key would overwrite
  # an existing field.
  # This condition also checks if the class has any descendants, because
  # if it doesn't then it doesn't need a discriminator key.
  if !fields.has_key?(self.discriminator_key) && !descendants.empty?
    default_proc = lambda { self.class.discriminator_value }
    field(self.discriminator_key, default: default_proc, type: String)
  end
end
discriminator_value=(value) click to toggle source
# File lib/mongoid/traversable.rb, line 56
def discriminator_value=(value)
  value ||= self.name
  _mongoid_clear_types
  add_discriminator_mapping(value)
  @discriminator_value = value
end