Module: Mongoid::Traversable::DiscriminatorAssignment Private

Defined in:
lib/mongoid/traversable.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Module used for prepending to the various discriminator_*= methods

Instance Method Summary collapse

Instance Method Details

#discriminator_key=(value) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Sets the discriminator key.

rubocop:disable Metrics/AbcSize

Parameters:

  • value (String)

    The discriminator key to set.

Raises:



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/mongoid/traversable.rb', line 135

def discriminator_key=(value)
  raise Errors::InvalidDiscriminatorKeyTarget.new(self, superclass) if hereditary?

  _mongoid_clear_types

  if value
    Mongoid::Fields::Validators::Macro.validate_field_name(self, value)
    value = value.to_s
    ::Mongoid::Traversable.__redefine(self, 'discriminator_key', value)
  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.
  return if fields.key?(discriminator_key) || descendants.empty?

  default_proc = -> { self.class.discriminator_value }
  field(discriminator_key, default: default_proc, type: String)
end

#discriminator_value=(value) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the discriminator key.

Returns:

  • (String)

    The discriminator key.



169
170
171
172
173
174
# File 'lib/mongoid/traversable.rb', line 169

def discriminator_value=(value)
  value ||= name
  _mongoid_clear_types
  add_discriminator_mapping(value)
  @discriminator_value = value
end