From 5dd7e985ae81675e1db274f13febf72479d1ecae Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 20:30:24 +0900 Subject: [PATCH 01/14] - Prefer defining field type value as a symbol rather than a class. (Symbol is actually supported today.) - Add ability to define custom field types. --- docs/reference/fields.txt | 215 ++++++++++++++++------- lib/config/locales/en.yml | 36 +++- lib/mongoid/errors/invalid_field_type.rb | 25 +++ lib/mongoid/field_types.rb | 63 +++++++ lib/mongoid/fields.rb | 66 ++++--- 5 files changed, 298 insertions(+), 107 deletions(-) create mode 100644 lib/mongoid/errors/invalid_field_type.rb create mode 100644 lib/mongoid/field_types.rb diff --git a/docs/reference/fields.txt b/docs/reference/fields.txt index 59fa144087..3c5a926a95 100644 --- a/docs/reference/fields.txt +++ b/docs/reference/fields.txt @@ -13,15 +13,21 @@ Field Definition :class: singlecol +.. _field-types: + Field Types =========== -Even though MongoDB is a schemaless database and allows data to be stored -as strings, Mongoid permits the application to declare the type of data -stored in the various fields of a document. Field type declarations affect -the following: +MongoDB stores underlying document data using +`BSON types `_, and +Mongoid converts BSON types to Ruby types at runtime in your application. +For example, a field defined with `type: :float` will use the Ruby ``Float`` +class in-memory and will persist in the database as the the BSON ``double`` type. + +Field type definitions determine how Mongoid behaves when constructing queries +and retrieving/writing fields from/to the database. Specifically: -1. When assigning values to fields, the values are converted to the +1. When assigning values to fields at runtime, the values are converted to the specified type. 2. When persisting data to MongoDB, the data is sent in an appropriate @@ -34,9 +40,7 @@ type before being sent to MongoDB. 4. When retrieving documents from the database, field values are converted to the specified type. -Field type definitions determine how Mongoid behaves when constructing the -queries, retrieving and writing fields from the database. Changing the field -definitions in a model class does not alter data already stored in +Changing the field definitions in a model class does not alter data already stored in MongoDB. To update type or contents of fields of existing documents, the field must be re-saved to the database. Note that, due to Mongoid tracking which attributes on a model change and only saving the changed ones, @@ -44,38 +48,51 @@ it may be necessary to explicitly write a field value when changing the type of an existing field without changing the stored values. Consider a simple class for modeling a person in an application. A person may -have a first name, last name, and middle name. We can define these attributes +have a name, date_of_birth, and weight. We can define these attributes on a person by using the ``field`` macro. .. code-block:: ruby class Person include Mongoid::Document - field :first_name, type: String - field :middle_name, type: String - field :last_name, type: String + field :name, type: :string + field :date_of_birth, type: :date + field :weight, type: :float end Below is a list of valid types for fields. -- ``Array`` -- ``BigDecimal`` -- ``Boolean`` -- ``Date`` -- ``DateTime`` -- ``Float`` -- ``Hash`` -- ``Integer`` -- ``BSON::ObjectId`` -- ``BSON::Binary`` -- ``Range`` -- ``Regexp`` -- ``Set`` -- ``String`` -- ``StringifiedSymbol`` -- ``Symbol`` -- ``Time`` -- ``TimeWithZone`` +- ``:array`` +- ``:big_decimal`` +- ``:boolean`` +- ``:date`` +- ``:date_time`` +- ``:decimal128`` (``BSON::Decimal128``) +- ``:float`` +- ``:hash`` +- ``:integer`` +- ``:object_id`` (``BSON::ObjectID``) +- ``:binary`` (``BSON::Binary``) +- ``:range`` +- ``:regexp`` +- ``:set`` +- ``:string`` +- ``:stringified_symbol`` (see below) +- ``:symbol`` +- ``:time`` +- ``:time_with_zone`` + +To define custom field types, refer to :ref:`Custom Field Types ` below. + +As of Mongoid 7.5, ``field :type`` should be specified as a ``Symbol``. +Specifying as a ``Class`` is deprecated and will be no longer supported in Mongoid 8.0. +Unrecognized field type symbols will result in an `InvalidFieldType` error when the model class is loaded. + + +.. _omitting-field-type-definition: + +Omitting Field Type Definition +------------------------------ If you decide not to specify the type of field with the definition, Mongoid will treat it as an object and not try to typecast it when sending the values to the database. @@ -103,18 +120,18 @@ Types that are not supported as dynamic attributes since they cannot be cast are - ``Range`` -.. _stringified-symbol: +.. _field-type-stringified-symbol: -The StringifiedSymbol Type --------------------------- +Field Type :stringified_symbol +------------------------------ -The ``StringifiedSymbol`` field type is the recommended field type for storing -values that should be exposed as symbols to Ruby applications. When using the ``Symbol`` field type, +The ``:stringified_symbol`` field type is the recommended field type for storing +values that should be exposed as symbols to Ruby applications. When using the ``:symbol`` field type, Mongoid defaults to storing values as BSON symbols. For more information on the -BSON symbol type, see :ref:`here `. +BSON symbol type, see :ref:`here `. However, the BSON symbol type is deprecated and is difficult to work with in programming languages -without native symbol types, so the ``StringifiedSymbol`` type allows the use of symbols -while ensuring interoperability with other drivers. The ``StringifiedSymbol`` type stores all data +without native symbol types, so the ``:stringified_symbol`` type allows the use of symbols +while ensuring interoperability with other drivers. The ``:stringified_symbol`` type stores all data on the database as strings, while exposing values to the application as symbols. An example usage is shown below: @@ -157,12 +174,12 @@ migration from fields that currently store either strings or BSON symbols in the ``StringifiedSymbol`` field type. -.. _bson-symbol: +.. _field-type-symbol: -BSON Symbol Type ----------------- +Field Type :symbol +------------------ -New applications should use the :ref:`StringifiedSymbol field type ` +New applications should use the :ref:`StringifiedSymbol field type ` to store Ruby symbols in the database. The ``StringifiedSymbol`` field type provides maximum compatibility with other applications and programming languages and has the same behavior in all circumstances. @@ -188,8 +205,10 @@ snippet in your project: end -Hash Fields ------------ +.. _field-type-hash: + +Field Type :hash +---------------- When using a field of type Hash, be wary of adhering to the `legal key names for mongoDB `_, @@ -218,8 +237,10 @@ or else the values will not store properly. end -Time Fields ------------ +.. _field-type-time: + +Field Type :time +---------------- ``Time`` fields store values as ``Time`` instances in the :ref:`configured time zone `. @@ -242,8 +263,10 @@ In the above example, the value was interpreted as the beginning of today in local time, because the application was not configured to use UTC times. -Date Fields ------------ +.. _field-type-date: + +Field Type :date +---------------- Mongoid allows assignment of values of several types to ``Date`` fields: @@ -265,11 +288,14 @@ recommended to explicitly convert ``String``, ``Time`` and ``DateTime`` objects to ``Date`` objects before assigning the values to fields of type ``Date``. -DateTime Fields ---------------- + +.. _field-type-date-time: + +Field Type :date_time +--------------------- MongoDB stores all times as UTC timestamps. When assigning a value to a -``DateTime`` field, or when querying a ``DateTime`` field, Mongoid +``:date_time`` field, or when querying a ``:date_time`` field, Mongoid converts the passed in value to a UTC ``Time`` before sending it to the MongoDB server. @@ -332,13 +358,13 @@ If a time zone is specified, it is respected: # => Sun, 04 Mar 2018 09:00:00 +0000 -.. _regular-expression-fields: +.. _field-type-regexp: -Regular Expression Fields -------------------------- +Field Type :regexp +------------------ MongoDB supports storing regular expressions in documents, and querying using -regular expressions. Of note for Ruby applications, MongoDB uses +regular expressions. Note that MongoDB uses `Perl-compatible regular expressions (PCRE) `_ and Ruby uses `Onigmo `_, which is a fork of `Oniguruma regular expression engine `_. @@ -396,8 +422,10 @@ This is because the meaning of ``$`` is different between PCRE and Ruby regular expressions. -Defaults --------- +.. _field-default-values: + +Specifying Field Default Values +------------------------------- A field can be configured to have a default value. The default value can be fixed, as in the following example: @@ -587,7 +615,7 @@ To define the field anyway, use the ``overwrite: true`` option: .. _custom-id: -Custom Ids +Custom IDs ---------- By default, Mongoid defines the ``_id`` field on documents to contain a @@ -640,16 +668,20 @@ alias can :ref:`be removed ` if desired (such as to integrate with systems that use the ``id`` field to store value different from ``_id``. +.. _customizing-field-behavior: + Customizing Field Behavior ========================== -Mongoid offers several options for customizing the behavior of fields. +Mongoid offers several ways to customize the behavior of fields. + +.. _custom-getters-and-setters: Custom Getters And Setters -------------------------- -You can define custom getters and setters for fields to modify the values +You may override getters and setters for fields to modify the values when they are being accessed or written. The getters and setters use the same name as the field. Use ``read_attribute`` and ``write_attribute`` methods inside the getters and setters to operate on the raw attribute @@ -707,20 +739,37 @@ may be implemented as follows: # => {"_id"=>BSON::ObjectId('613fa15aa15d5d617216104c'), "value"=>2.0, "unit"=>nil} +.. _custom-field-types: + Custom Field Types ------------------ You can define custom types in Mongoid and determine how they are serialized -and deserialized. You simply need to provide three methods on it for Mongoid -to call to convert your object to and from MongoDB friendly values. +and deserialized. In this example, we define a new field type ``Point``, which we +can use in our model class as follows: .. code-block:: ruby class Profile include Mongoid::Document - field :location, type: Point + field :location, type: :point + end + +First, declare the new field type mapping in an initializer: + +.. code-block:: ruby + + # in /config/initializers/mongoid_custom_fields.rb + + Mongoid::Fields.configure do + type :point, Point end +Then make a Ruby class to represent the type. This class must +define ``mongoize`` and ``demongoize`` methods as per below: + +.. code-block:: ruby + class Point attr_reader :x, :y @@ -730,6 +779,7 @@ to call to convert your object to and from MongoDB friendly values. end # Converts an object of this instance into a database friendly value. + # In this example, we store the values in the database as array. def mongoize [ x, y ] end @@ -795,12 +845,49 @@ Note that when accessing custom fields from the document, you will get a new instance of that object with each call to the getter. This is because Mongoid is generating a new object from the raw attributes on each access. -We need the point object in the criteria to be transformed to a +We need the ``Point`` object in the criteria to be transformed to a MongoDB-friendly value when it is not as well, ``evolve`` is the method that takes care of this. We check if the passed in object is a ``Point`` first, in case we also want to be able to pass in ordinary arrays instead. +.. _custom-field-options: + +Custom Field Options +-------------------- + +You may define custom options for the ``field`` macro function +which extend its behavior at the your time model classes are loaded. + +As an example, we will define a ``:required`` option which will +add a presence validator for the field. First, declare the new +field option in an initializer: + +.. code-block:: ruby + + # in /config/initializers/mongoid_custom_fields.rb + + Mongoid::Fields.configure do + option :required do |model, field, value| + model.validates_presence_of field if value + end + end + +Then, use it your model class: + +.. code-block:: ruby + + class Person + include Mongoid::Document + + field :name, type: String, required: true + end + +No assumptions are made about the functionality the handler might +perform. The handler will always be called whenever the option is used +in the field definition, even if its value is false or nil. + + .. _dynamic-fields: Dynamic Fields diff --git a/lib/config/locales/en.yml b/lib/config/locales/en.yml index 9f3b6337f1..d639e0533b 100644 --- a/lib/config/locales/en.yml +++ b/lib/config/locales/en.yml @@ -84,7 +84,7 @@ en: message: "Empty configuration file: %{path}." summary: "Your mongoid.yml configuration file appears to be empty." resolution: "Ensure your configuration file contains the correct contents. - Please consult the following page with respect to Mongoid's configuration: + Refer to: https://docs.mongodb.com/mongoid/current/reference/configuration/" invalid_collection: message: "Access to the collection for %{klass} is not allowed." @@ -105,7 +105,7 @@ en: summary: "Your mongoid.yml configuration file does not contain the correct file structure." resolution: "Ensure your configuration file contains the correct contents. - Please consult the following page with respect to Mongoid's configuration: + Refer to: https://docs.mongodb.com/mongoid/current/reference/configuration/" invalid_config_option: message: "Invalid configuration option: %{name}." @@ -173,14 +173,34 @@ en: field definition in order to prevent unexpected behavior later on." resolution: "When defining the field :%{name} on '%{klass}', please provide valid options for the field. These are currently: %{valid}. If you - meant to define a custom field option, please do so first like so:\n\n - \_\_Mongoid::Fields.option :%{option} do |model, field, value|\n - \_\_\_\_# Your logic here...\n + meant to define a custom field option, please do so first as follows:\n\n + \_\_Mongoid::Fields.configure do\n + \_\_\_\_option :%{option} do |model, field, value|\n + \_\_\_\_\_\_# Your logic here...\n + \_\_\_\_end\n \_\_end\n \_\_class %{klass}\n \_\_\_\_include Mongoid::Document\n \_\_\_\_field :%{name}, %{option}: true\n - \_\_end\n\n" + \_\_end\n\n + Refer to: + https://docs.mongodb.com/mongoid/current/reference/fields/#custom-field-options" + invalid_field_type: + message: "Invalid field type :%{type} for field :%{field} on model '%{klass}'." + summary: "Model '%{klass}' defines a field :%{field} with an unknown :type value + '%{type}'. This value is neither present in Mongoid's default type mapping, + nor defined in a custom field type mapping." + resolution: "Please provide a valid :type value for the field. If you + meant to define a custom field type, please do so first as follows:\n\n + \_\_Mongoid::Fields.configure do\n + \_\_\_\_type :%{type}, YourTypeClass + \_\_end\n + \_\_class %{klass}\n + \_\_\_\_include Mongoid::Document\n + \_\_\_\_field :%{field}, type: :%{type}\n + \_\_end\n\n + Refer to: + https://docs.mongodb.com/mongoid/current/reference/fields/#custom-field-types" invalid_includes: message: "Invalid includes directive: %{klass}.includes(%{args})" summary: "Eager loading in Mongoid only supports providing arguments @@ -564,12 +584,12 @@ en: Mongoid::Attributes::Dynamic in %{klass} if you intend to store values in fields that are not explicitly defined." unknown_model: - message: "Attempted to instantiate an object of the unknown Model '%{klass}'." + message: "Attempted to instantiate an object of the unknown model '%{klass}'." summary: "A document with the value '%{value}' at the key '_type' was used to instantiate a model object but Mongoid cannot find this Class." resolution: "The _type field is a reserved one used by Mongoid to determine the class for instantiating an object. Please don't save data in this field or ensure - that any values in this field correspond to valid Models." + that any values in this field correspond to valid models." unsaved_document: message: "Attempted to save %{document} before the parent %{base}." summary: "You cannot call create or create! through the diff --git a/lib/mongoid/errors/invalid_field_type.rb b/lib/mongoid/errors/invalid_field_type.rb new file mode 100644 index 0000000000..403866d254 --- /dev/null +++ b/lib/mongoid/errors/invalid_field_type.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module Mongoid + module Errors + + # This error is raised when trying to define a field using a :type option value + # that is not present in the field type mapping. + class InvalidFieldType < MongoidError + + # Create the new error. + # + # @example Instantiate the error. + # InvalidFieldType.new('Person', 'first_name', 'stringgy') + # + # @param [ String ] klass The model class. + # @param [ String ] field The field on which the invalid type is used. + # @param [ String ] type The value of the field :type option. + def initialize(klass, field, type) + super( + compose_message('invalid_field_type', { klass: klass, field: field, type: type }) + ) + end + end + end +end diff --git a/lib/mongoid/field_types.rb b/lib/mongoid/field_types.rb new file mode 100644 index 0000000000..a6503b41c0 --- /dev/null +++ b/lib/mongoid/field_types.rb @@ -0,0 +1,63 @@ +# frozen_string_literal: true + +module Mongoid + + # Singleton module which contains a cache for field type definitions. + # Custom field types can be configured. + module FieldTypes + extend self + + # For fields defined with symbols use the correct class. + DEFAULT_MAPPING = { + array: Array, + bigdecimal: BigDecimal, + big_decimal: BigDecimal, + binary: BSON::Binary, + boolean: Mongoid::Boolean, + date: Date, + datetime: DateTime, + date_time: DateTime, + decimal128: BSON::Decimal128, + double: Float, + float: Float, + hash: Hash, + integer: Integer, + object: Object, + object_id: BSON::ObjectId, + range: Range, + regexp: Regexp, + set: Set, + string: String, + stringified_symbol: Mongoid::StringifiedSymbol, + symbol: Symbol, + time: Time, + time_with_zone: ActiveSupport::TimeWithZone + }.with_indifferent_access.freeze + + def get(value) + mapping[value] || handle_unmapped_type(value) + end + + def define(symbol, klass) + mapping[symbol] = klass + end + + delegate :delete, to: :mapping + + def mapping + @mapping ||= DEFAULT_MAPPING.dup + end + + def handle_unmapped_type(type) + return Object if type.nil? + + if type.is_a?(Module) + Mongoid.logger.warn(FIELD_TYPE_IS_SYMBOL) + return Mongoid::Boolean if type.to_s == 'Boolean' + type + end + + nil + end + end +end diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index d9b072f2d8..3e09ad7837 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -11,30 +11,6 @@ module Mongoid module Fields extend ActiveSupport::Concern - StringifiedSymbol = Mongoid::StringifiedSymbol - Boolean = Mongoid::Boolean - - # For fields defined with symbols use the correct class. - TYPE_MAPPINGS = { - array: Array, - big_decimal: BigDecimal, - binary: BSON::Binary, - boolean: Mongoid::Boolean, - date: Date, - date_time: DateTime, - float: Float, - hash: Hash, - integer: Integer, - object_id: BSON::ObjectId, - range: Range, - regexp: Regexp, - set: Set, - string: String, - stringified_symbol: StringifiedSymbol, - symbol: Symbol, - time: Time - }.with_indifferent_access - # Constant for all names of the _id field in a document. # # This does not include aliases of _id field. @@ -205,16 +181,39 @@ def using_object_ids? class << self + # DSL method used for configuration readability, typically in + # an initializer. + # + # @example + # Mongoid::Fields.configure do + # # do configuration + # end + def configure(&block) + instance_exec(&block) + end + + # Defines a field type mapping, for later use in field :type option. + # + # @example + # Mongoid::Fields.configure do + # type :point, Point + # end + def type(symbol, klass) + Mongoid::FieldTypes.define(symbol, klass) + end + # Stores the provided block to be run when the option name specified is # defined on a field. # - # No assumptions are made about what sort of work the handler might + # No assumptions are made about the functionality the handler might # perform, so it will always be called if the `option_name` key is # provided in the field definition -- even if it is false or nil. # # @example - # Mongoid::Fields.option :required do |model, field, value| - # model.validates_presence_of field if value + # Mongoid::Fields.configure do + # option :required do |model, field, value| + # model.validates_presence_of field if value + # end # end # # @param [ Symbol ] option_name the option name to match against @@ -569,19 +568,16 @@ def remove_defaults(name) def field_for(name, options) opts = options.merge(klass: self) - type_mapping = TYPE_MAPPINGS[options[:type]] - opts[:type] = type_mapping || unmapped_type(options) + opts[:type] = field_type_klass_for(name, options[:type]) return Fields::Localized.new(name, opts) if options[:localize] return Fields::ForeignKey.new(name, opts) if options[:identity] Fields::Standard.new(name, opts) end - def unmapped_type(options) - if "Boolean" == options[:type].to_s - Mongoid::Boolean - else - options[:type] || Object - end + def field_type_klass_for(field, type) + klass = FieldTypes.get(type) + return klass if klass + raise Mongoid::Errors::InvalidFieldType.new(self.name, field, type) end end end From fca40d297f3d6933f78b8a6beb615382891a5bf2 Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 21:08:35 +0900 Subject: [PATCH 02/14] Fix deprecation + add release notes --- docs/release-notes/mongoid-7.5.txt | 45 ++++++++++++++++++++++++++---- lib/mongoid/field_types.rb | 6 +++- 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/docs/release-notes/mongoid-7.5.txt b/docs/release-notes/mongoid-7.5.txt index ace57a437b..a4d02040f5 100644 --- a/docs/release-notes/mongoid-7.5.txt +++ b/docs/release-notes/mongoid-7.5.txt @@ -21,7 +21,7 @@ the complete list of issues fixed in each release, including bug fixes. Order of Callbacks Invocation ----------------------------- -**Breaking change:** Mongoid 7.5 changes order of _create and _save callbacks +**Breaking change:** Mongoid 7.5 changes the order of _create and _save callback invocation for documents with associations. Referenced associations (``has_one`` and ``has_many``): @@ -119,12 +119,11 @@ Embedded associations (``embeds_one`` and ``embeds_many``): +---------------------------------------+---------------------------------------+ -``Changeable`` Module Behavior Made Compatible With ``ActiveModel::Ditry`` +``Changeable`` Module Behavior Made Compatible With ``ActiveModel::Dirty`` -------------------------------------------------------------------------- When updating documents, it is now possible to get updated attribute values -in ``after_*`` callbacks. This is following with ActiveRecord/ActiveModel -behavior. +in ``after_*`` callbacks. This follows ActiveRecord/ActiveModel behavior. .. code-block:: ruby @@ -159,4 +158,40 @@ Mongoid 7.4 output: nil Notice that in 7.4 ``attribute_was(:age)`` returns an old attribute value, -while in 7.5 ``attribute_was(:age)`` returns the new values, \ No newline at end of file +while in 7.5 ``attribute_was(:age)`` returns the new values. + + +Setting Field Type as a Class is Deprecated +------------------------------------------- + +Mongoid has historically supported defining the ``field :type`` option +as either a Symbol or a Class. As of Mongoid 7.5, using a Class is deprecated +and Symbol is preferred. Support for Class will be removed entirely in Mongoid 8.0. + +.. code-block:: ruby + + class Person + include Mongoid::Document + + # Deprecated; will log an warning message. + field :first_name, type: String + + # Good + field :last_name, type: :string + end + + +Support for Defining Custom Field Type Values +--------------------------------------------- + +Mongoid 7.5 adds the ability to define custom ``field :type`` Symbol values as follows: + +.. code-block:: ruby + + # in /config/initializers/mongoid_custom_fields.rb + + Mongoid::Fields.configure do + type :point, Point + end + +Refer to the :ref:`docs ` for details. diff --git a/lib/mongoid/field_types.rb b/lib/mongoid/field_types.rb index a6503b41c0..d76445c787 100644 --- a/lib/mongoid/field_types.rb +++ b/lib/mongoid/field_types.rb @@ -52,7 +52,11 @@ def handle_unmapped_type(type) return Object if type.nil? if type.is_a?(Module) - Mongoid.logger.warn(FIELD_TYPE_IS_SYMBOL) + symbol = type.name.demodulize.underscore + Mongoid.logger.warn( + "Using a Class (#{type}) as the field :type option is deprecated and will be removed in Mongoid 8.0. " + + "Please use a Symbol (:#{symbol}) instead." + ) return Mongoid::Boolean if type.to_s == 'Boolean' type end From 21d7fcd629bbdcec7810d0cdc3ef127e98d8ec91 Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 22:02:43 +0900 Subject: [PATCH 03/14] Improve docs primarily for the "Fields" page, as well as a few small things for clarity in various places. This also adds documentation for previously undocumented "Custom Field Options" functionality (Mongoid::Fields.option) --- docs/reference/fields.txt | 202 +++++++++++++++++++---------- docs/release-notes/mongoid-7.5.txt | 13 +- lib/config/locales/en.yml | 12 +- lib/mongoid/fields.rb | 2 +- 4 files changed, 144 insertions(+), 85 deletions(-) diff --git a/docs/reference/fields.txt b/docs/reference/fields.txt index 59fa144087..06255e54fc 100644 --- a/docs/reference/fields.txt +++ b/docs/reference/fields.txt @@ -13,15 +13,21 @@ Field Definition :class: singlecol +.. _field-types: + Field Types =========== -Even though MongoDB is a schemaless database and allows data to be stored -as strings, Mongoid permits the application to declare the type of data -stored in the various fields of a document. Field type declarations affect -the following: +MongoDB stores underlying document data using +`BSON types `_, and +Mongoid converts BSON types to Ruby types at runtime in your application. +For example, a field defined with `type: :float` will use the Ruby ``Float`` +class in-memory and will persist in the database as the the BSON ``double`` type. + +Field type definitions determine how Mongoid behaves when constructing queries +and retrieving/writing fields from/to the database. Specifically: -1. When assigning values to fields, the values are converted to the +1. When assigning values to fields at runtime, the values are converted to the specified type. 2. When persisting data to MongoDB, the data is sent in an appropriate @@ -34,9 +40,7 @@ type before being sent to MongoDB. 4. When retrieving documents from the database, field values are converted to the specified type. -Field type definitions determine how Mongoid behaves when constructing the -queries, retrieving and writing fields from the database. Changing the field -definitions in a model class does not alter data already stored in +Changing the field definitions in a model class does not alter data already stored in MongoDB. To update type or contents of fields of existing documents, the field must be re-saved to the database. Note that, due to Mongoid tracking which attributes on a model change and only saving the changed ones, @@ -44,16 +48,16 @@ it may be necessary to explicitly write a field value when changing the type of an existing field without changing the stored values. Consider a simple class for modeling a person in an application. A person may -have a first name, last name, and middle name. We can define these attributes +have a name, date_of_birth, and weight. We can define these attributes on a person by using the ``field`` macro. .. code-block:: ruby class Person include Mongoid::Document - field :first_name, type: String - field :middle_name, type: String - field :last_name, type: String + field :name, type: String + field :date_of_birth, type: Date + field :weight, type: Float end Below is a list of valid types for fields. @@ -77,6 +81,14 @@ Below is a list of valid types for fields. - ``Time`` - ``TimeWithZone`` +To define custom field types, refer to :ref:`Custom Field Types ` below. + + +.. _omitting-field-type-definition: + +Omitting Field Type Definition +------------------------------ + If you decide not to specify the type of field with the definition, Mongoid will treat it as an object and not try to typecast it when sending the values to the database. This can be advantageous as the lack of attempted conversion will yield a slight @@ -103,15 +115,15 @@ Types that are not supported as dynamic attributes since they cannot be cast are - ``Range`` -.. _stringified-symbol: +.. _field-type-stringified-symbol: -The StringifiedSymbol Type --------------------------- +Field Type: StringifiedSymbol +----------------------------- The ``StringifiedSymbol`` field type is the recommended field type for storing values that should be exposed as symbols to Ruby applications. When using the ``Symbol`` field type, Mongoid defaults to storing values as BSON symbols. For more information on the -BSON symbol type, see :ref:`here `. +BSON symbol type, see :ref:`here `. However, the BSON symbol type is deprecated and is difficult to work with in programming languages without native symbol types, so the ``StringifiedSymbol`` type allows the use of symbols while ensuring interoperability with other drivers. The ``StringifiedSymbol`` type stores all data @@ -157,12 +169,12 @@ migration from fields that currently store either strings or BSON symbols in the ``StringifiedSymbol`` field type. -.. _bson-symbol: +.. _field-type-symbol: -BSON Symbol Type ----------------- +Field Type: Symbol +------------------ -New applications should use the :ref:`StringifiedSymbol field type ` +New applications should use the :ref:`StringifiedSymbol field type ` to store Ruby symbols in the database. The ``StringifiedSymbol`` field type provides maximum compatibility with other applications and programming languages and has the same behavior in all circumstances. @@ -188,8 +200,10 @@ snippet in your project: end -Hash Fields ------------ +.. _field-type-hash: + +Field Type: Hash +---------------- When using a field of type Hash, be wary of adhering to the `legal key names for mongoDB `_, @@ -218,8 +232,10 @@ or else the values will not store properly. end -Time Fields ------------ +.. _field-type-time: + +Field Type: Time +---------------- ``Time`` fields store values as ``Time`` instances in the :ref:`configured time zone `. @@ -242,8 +258,10 @@ In the above example, the value was interpreted as the beginning of today in local time, because the application was not configured to use UTC times. -Date Fields ------------ +.. _field-type-date: + +Field Type: Date +---------------- Mongoid allows assignment of values of several types to ``Date`` fields: @@ -265,8 +283,11 @@ recommended to explicitly convert ``String``, ``Time`` and ``DateTime`` objects to ``Date`` objects before assigning the values to fields of type ``Date``. -DateTime Fields ---------------- + +.. _field-type-date-time: + +Field Type: DateTime +--------------------- MongoDB stores all times as UTC timestamps. When assigning a value to a ``DateTime`` field, or when querying a ``DateTime`` field, Mongoid @@ -332,13 +353,13 @@ If a time zone is specified, it is respected: # => Sun, 04 Mar 2018 09:00:00 +0000 -.. _regular-expression-fields: +.. _field-type-regexp: -Regular Expression Fields -------------------------- +Field Type: Regexp +------------------ MongoDB supports storing regular expressions in documents, and querying using -regular expressions. Of note for Ruby applications, MongoDB uses +regular expressions. Note that MongoDB uses `Perl-compatible regular expressions (PCRE) `_ and Ruby uses `Onigmo `_, which is a fork of `Oniguruma regular expression engine `_. @@ -396,8 +417,10 @@ This is because the meaning of ``$`` is different between PCRE and Ruby regular expressions. -Defaults --------- +.. _field-default-values: + +Specifying Field Default Values +------------------------------- A field can be configured to have a default value. The default value can be fixed, as in the following example: @@ -587,7 +610,7 @@ To define the field anyway, use the ``overwrite: true`` option: .. _custom-id: -Custom Ids +Custom IDs ---------- By default, Mongoid defines the ``_id`` field on documents to contain a @@ -640,16 +663,20 @@ alias can :ref:`be removed ` if desired (such as to integrate with systems that use the ``id`` field to store value different from ``_id``. +.. _customizing-field-behavior: + Customizing Field Behavior ========================== -Mongoid offers several options for customizing the behavior of fields. +Mongoid offers several ways to customize the behavior of fields. +.. _custom-getters-and-setters: + Custom Getters And Setters -------------------------- -You can define custom getters and setters for fields to modify the values +You may override getters and setters for fields to modify the values when they are being accessed or written. The getters and setters use the same name as the field. Use ``read_attribute`` and ``write_attribute`` methods inside the getters and setters to operate on the raw attribute @@ -707,12 +734,14 @@ may be implemented as follows: # => {"_id"=>BSON::ObjectId('613fa15aa15d5d617216104c'), "value"=>2.0, "unit"=>nil} +.. _custom-field-types: + Custom Field Types ------------------ You can define custom types in Mongoid and determine how they are serialized -and deserialized. You simply need to provide three methods on it for Mongoid -to call to convert your object to and from MongoDB friendly values. +and deserialized. In this example, we define a new field type ``Point``, which we +can use in our model class as follows: .. code-block:: ruby @@ -721,6 +750,11 @@ to call to convert your object to and from MongoDB friendly values. field :location, type: Point end +Then make a Ruby class to represent the type. This class must define methods +used for MongoDB serialization and deserialization as follows: + +.. code-block:: ruby + class Point attr_reader :x, :y @@ -730,18 +764,13 @@ to call to convert your object to and from MongoDB friendly values. end # Converts an object of this instance into a database friendly value. + # In this example, we store the values in the database as array. def mongoize [ x, y ] end class << self - # Get the object as it was stored in the database, and instantiate - # this custom class from it. - def demongoize(object) - Point.new(object[0], object[1]) - end - # Takes any possible object and converts it to how it would be # stored in the database. def mongoize(object) @@ -752,8 +781,14 @@ to call to convert your object to and from MongoDB friendly values. end end + # Get the object as it was stored in the database, and instantiate + # this custom class from it. + def demongoize(object) + Point.new(object[0], object[1]) + end + # Converts the object that was supplied to a criteria and converts it - # into a database friendly form. + # into a query-friendly form. def evolve(object) case object when Point then object.mongoize @@ -763,42 +798,69 @@ to call to convert your object to and from MongoDB friendly values. end end -The instance method ``mongoize`` takes an instance of your object, and -converts it into how it will be stored in the database. In our example above, -we want to store our point object as an array in the form ``[ x, y ]``. +The instance method ``mongoize`` takes an instance of your custom type object, and +converts it into a represenation of how it will be stored in the database, i.e. to pass +to the MongoDB Ruby driver. In our example above, we want to store our ``Point`` +object as an ``Array`` in the form ``[ x, y ]``. -The class method ``demongoize`` takes an object as how it was stored in the -database, and is responsible for instantiating an object of your custom type. -In this case, we take an array and instantiate a ``Point`` from it. - -The class method ``mongoize`` takes an object that you would use to set on -your model from your application code, and create the object as it would be -stored in the database. This is for cases where you are not passing your -model instances of your custom type in the setter: +The class method ``mongoize`` is similar to the instance method, however it must handle +objects of all possible types as inputs. The ``mongoize`` method is used when calling the +setter methods for fields of your custom type. .. code-block:: ruby point = Point.new(12, 24) - venue = Venue.new(location: point) # This uses the mongoize instance method. - venue = Venue.new(location: [ 12, 24 ]) # This uses the mongoize class method. + venue = Venue.new(location: point) # This uses the Point#mongoize instance method. + venue = Venue.new(location: [ 12, 24 ]) # This uses the Point.mongoize class method. + +The class method ``demongoize`` does the inverse of ``mongoize``. It takes the raw object +from the MongoDB Ruby driver and converts it to an instance of your custom type. +In this case, the database driver returns an ``Array`` and we instantiate a ``Point`` from it. +The ``demongoize`` method is used when calling the getters of fields for your custom type. +Note that in the example above, since ``demongoize`` calls ``Point.new``, a new instance of +``Point`` will be generated on each call to the getter. -The class method ``evolve`` takes an object, and determines how it is to be -transformed for use in criteria. For example we may want to write a query -like so: +Lastly, the class method ``evolve`` is similar to ``mongoize``, however it is used +when transforming objects for use in Mongoid query criteria. .. code-block:: ruby point = Point.new(12, 24) - Venue.where(location: point) + Venue.where(location: point) # This uses Point.evolve + + +.. _custom-field-options: + +Custom Field Options +-------------------- -Note that when accessing custom fields from the document, you will get a -new instance of that object with each call to the getter. This is because -Mongoid is generating a new object from the raw attributes on each access. +You may define custom options for the ``field`` macro function +which extend its behavior at the your time model classes are loaded. + +As an example, we will define a ``:required`` option which will add a presence +validator for the field. First, declare the new field option in an initializer, +specifiying its handler function as a block: + +.. code-block:: ruby + + # in /config/initializers/mongoid_custom_fields.rb + + Mongoid::Fields.option :required do |model, field, value| + model.validates_presence_of field if value + end + +Then, use it your model class: + +.. code-block:: ruby + + class Person + include Mongoid::Document + + field :name, type: String, required: true + end -We need the point object in the criteria to be transformed to a -MongoDB-friendly value when it is not as well, ``evolve`` is the method -that takes care of this. We check if the passed in object is a ``Point`` -first, in case we also want to be able to pass in ordinary arrays instead. +Note that the handler function will be invoked whenever the option is used +in the field definition, even if the option's value is false or nil. .. _dynamic-fields: diff --git a/docs/release-notes/mongoid-7.5.txt b/docs/release-notes/mongoid-7.5.txt index ace57a437b..96ff1f6ee0 100644 --- a/docs/release-notes/mongoid-7.5.txt +++ b/docs/release-notes/mongoid-7.5.txt @@ -18,10 +18,10 @@ please consult GitHub releases for detailed release notes and JIRA for the complete list of issues fixed in each release, including bug fixes. -Order of Callbacks Invocation ------------------------------ +Order of Callback Invocation +---------------------------- -**Breaking change:** Mongoid 7.5 changes order of _create and _save callbacks +**Breaking change:** Mongoid 7.5 changes the order of _create and _save callback invocation for documents with associations. Referenced associations (``has_one`` and ``has_many``): @@ -119,12 +119,11 @@ Embedded associations (``embeds_one`` and ``embeds_many``): +---------------------------------------+---------------------------------------+ -``Changeable`` Module Behavior Made Compatible With ``ActiveModel::Ditry`` +``Changeable`` Module Behavior Made Compatible With ``ActiveModel::Dirty`` -------------------------------------------------------------------------- When updating documents, it is now possible to get updated attribute values -in ``after_*`` callbacks. This is following with ActiveRecord/ActiveModel -behavior. +in ``after_*`` callbacks. This follows ActiveRecord/ActiveModel behavior. .. code-block:: ruby @@ -159,4 +158,4 @@ Mongoid 7.4 output: nil Notice that in 7.4 ``attribute_was(:age)`` returns an old attribute value, -while in 7.5 ``attribute_was(:age)`` returns the new values, \ No newline at end of file +while in 7.5 ``attribute_was(:age)`` returns the new values. diff --git a/lib/config/locales/en.yml b/lib/config/locales/en.yml index 9f3b6337f1..c093a18ebc 100644 --- a/lib/config/locales/en.yml +++ b/lib/config/locales/en.yml @@ -84,8 +84,7 @@ en: message: "Empty configuration file: %{path}." summary: "Your mongoid.yml configuration file appears to be empty." resolution: "Ensure your configuration file contains the correct contents. - Please consult the following page with respect to Mongoid's configuration: - https://docs.mongodb.com/mongoid/current/reference/configuration/" + Refer to: https://docs.mongodb.com/mongoid/current/reference/configuration/" invalid_collection: message: "Access to the collection for %{klass} is not allowed." summary: "%{klass}.collection was called, and %{klass} is an embedded @@ -105,8 +104,7 @@ en: summary: "Your mongoid.yml configuration file does not contain the correct file structure." resolution: "Ensure your configuration file contains the correct contents. - Please consult the following page with respect to Mongoid's configuration: - https://docs.mongodb.com/mongoid/current/reference/configuration/" + Refer to: https://docs.mongodb.com/mongoid/current/reference/configuration/" invalid_config_option: message: "Invalid configuration option: %{name}." summary: "A invalid configuration option was provided in your @@ -173,7 +171,7 @@ en: field definition in order to prevent unexpected behavior later on." resolution: "When defining the field :%{name} on '%{klass}', please provide valid options for the field. These are currently: %{valid}. If you - meant to define a custom field option, please do so first like so:\n\n + meant to define a custom field option, please do so first as follows:\n\n \_\_Mongoid::Fields.option :%{option} do |model, field, value|\n \_\_\_\_# Your logic here...\n \_\_end\n @@ -564,12 +562,12 @@ en: Mongoid::Attributes::Dynamic in %{klass} if you intend to store values in fields that are not explicitly defined." unknown_model: - message: "Attempted to instantiate an object of the unknown Model '%{klass}'." + message: "Attempted to instantiate an object of the unknown model '%{klass}'." summary: "A document with the value '%{value}' at the key '_type' was used to instantiate a model object but Mongoid cannot find this Class." resolution: "The _type field is a reserved one used by Mongoid to determine the class for instantiating an object. Please don't save data in this field or ensure - that any values in this field correspond to valid Models." + that any values in this field correspond to valid models." unsaved_document: message: "Attempted to save %{document} before the parent %{base}." summary: "You cannot call create or create! through the diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index d9b072f2d8..35b8a4d9cd 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -208,7 +208,7 @@ class << self # Stores the provided block to be run when the option name specified is # defined on a field. # - # No assumptions are made about what sort of work the handler might + # No assumptions are made about what functionality the handler might # perform, so it will always be called if the `option_name` key is # provided in the field definition -- even if it is false or nil. # From db541db017a758541c2df4bd3aa3d655bba32f84 Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 22:03:26 +0900 Subject: [PATCH 04/14] One more fix --- docs/release-notes/mongoid-7.5.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/release-notes/mongoid-7.5.txt b/docs/release-notes/mongoid-7.5.txt index 96ff1f6ee0..3d0b521dc4 100644 --- a/docs/release-notes/mongoid-7.5.txt +++ b/docs/release-notes/mongoid-7.5.txt @@ -157,5 +157,5 @@ Mongoid 7.4 output: # nil -Notice that in 7.4 ``attribute_was(:age)`` returns an old attribute value, -while in 7.5 ``attribute_was(:age)`` returns the new values. +Notice that in 7.4 ``attribute_was(:age)`` returns the old attribute value, +while in 7.5 ``attribute_was(:age)`` returns the new value. From d65cdcc2c4deb430913e37000d181238a473c05a Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 22:13:14 +0900 Subject: [PATCH 05/14] One more change --- lib/config/locales/en.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/config/locales/en.yml b/lib/config/locales/en.yml index c093a18ebc..4942a5431d 100644 --- a/lib/config/locales/en.yml +++ b/lib/config/locales/en.yml @@ -178,7 +178,9 @@ en: \_\_class %{klass}\n \_\_\_\_include Mongoid::Document\n \_\_\_\_field :%{name}, %{option}: true\n - \_\_end\n\n" + \_\_end\n\n + Refer to: + https://docs.mongodb.com/mongoid/current/reference/fields/#custom-field-options" invalid_includes: message: "Invalid includes directive: %{klass}.includes(%{args})" summary: "Eager loading in Mongoid only supports providing arguments From 0fdb6b603f3a32c0beb20d7871d6f49ec6cddc5f Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 22:56:03 +0900 Subject: [PATCH 06/14] Fix field types --- lib/mongoid/fields.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index a1bb58dc6d..17523d78c1 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -575,7 +575,7 @@ def field_for(name, options) end def field_type_klass_for(field, type) - klass = FieldTypes.get(type) + klass = Mongoid::FieldTypes.get(type) return klass if klass raise Mongoid::Errors::InvalidFieldType.new(self.name, field, type) end From 83d37c3a0900475158c6dc4071386e2c54cc7f50 Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 23:06:21 +0900 Subject: [PATCH 07/14] Add spec for InvalidFieldType --- lib/config/locales/en.yml | 2 +- lib/mongoid/errors.rb | 1 + lib/mongoid/field_types.rb | 67 ------------------ lib/mongoid/fields.rb | 5 +- lib/mongoid/fields/field_types.rb | 69 +++++++++++++++++++ .../mongoid/errors/invalid_field_type_spec.rb | 31 +++++++++ 6 files changed, 105 insertions(+), 70 deletions(-) delete mode 100644 lib/mongoid/field_types.rb create mode 100644 lib/mongoid/fields/field_types.rb create mode 100644 spec/mongoid/errors/invalid_field_type_spec.rb diff --git a/lib/config/locales/en.yml b/lib/config/locales/en.yml index 089f642d11..0e00a818dc 100644 --- a/lib/config/locales/en.yml +++ b/lib/config/locales/en.yml @@ -186,7 +186,7 @@ en: invalid_field_type: message: "Invalid field type :%{type} for field :%{field} on model '%{klass}'." summary: "Model '%{klass}' defines a field :%{field} with an unknown :type value - '%{type}'. This value is neither present in Mongoid's default type mapping, + :%{type}. This value is neither present in Mongoid's default type mapping, nor defined in a custom field type mapping." resolution: "Please provide a valid :type value for the field. If you meant to define a custom field type, please do so first as follows:\n\n diff --git a/lib/mongoid/errors.rb b/lib/mongoid/errors.rb index e530c54f88..dc36124e76 100644 --- a/lib/mongoid/errors.rb +++ b/lib/mongoid/errors.rb @@ -15,6 +15,7 @@ require "mongoid/errors/invalid_dependent_strategy" require "mongoid/errors/invalid_field" require "mongoid/errors/invalid_field_option" +require "mongoid/errors/invalid_field_type" require "mongoid/errors/invalid_find" require "mongoid/errors/invalid_includes" require "mongoid/errors/invalid_index" diff --git a/lib/mongoid/field_types.rb b/lib/mongoid/field_types.rb deleted file mode 100644 index d76445c787..0000000000 --- a/lib/mongoid/field_types.rb +++ /dev/null @@ -1,67 +0,0 @@ -# frozen_string_literal: true - -module Mongoid - - # Singleton module which contains a cache for field type definitions. - # Custom field types can be configured. - module FieldTypes - extend self - - # For fields defined with symbols use the correct class. - DEFAULT_MAPPING = { - array: Array, - bigdecimal: BigDecimal, - big_decimal: BigDecimal, - binary: BSON::Binary, - boolean: Mongoid::Boolean, - date: Date, - datetime: DateTime, - date_time: DateTime, - decimal128: BSON::Decimal128, - double: Float, - float: Float, - hash: Hash, - integer: Integer, - object: Object, - object_id: BSON::ObjectId, - range: Range, - regexp: Regexp, - set: Set, - string: String, - stringified_symbol: Mongoid::StringifiedSymbol, - symbol: Symbol, - time: Time, - time_with_zone: ActiveSupport::TimeWithZone - }.with_indifferent_access.freeze - - def get(value) - mapping[value] || handle_unmapped_type(value) - end - - def define(symbol, klass) - mapping[symbol] = klass - end - - delegate :delete, to: :mapping - - def mapping - @mapping ||= DEFAULT_MAPPING.dup - end - - def handle_unmapped_type(type) - return Object if type.nil? - - if type.is_a?(Module) - symbol = type.name.demodulize.underscore - Mongoid.logger.warn( - "Using a Class (#{type}) as the field :type option is deprecated and will be removed in Mongoid 8.0. " + - "Please use a Symbol (:#{symbol}) instead." - ) - return Mongoid::Boolean if type.to_s == 'Boolean' - type - end - - nil - end - end -end diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index 17523d78c1..48107a9738 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -4,6 +4,7 @@ require "mongoid/fields/foreign_key" require "mongoid/fields/localized" require "mongoid/fields/validators" +require "mongoid/fields/field_types" module Mongoid @@ -199,7 +200,7 @@ def configure(&block) # type :point, Point # end def type(symbol, klass) - Mongoid::FieldTypes.define(symbol, klass) + Fields::FieldTypes.define(symbol, klass) end # Stores the provided block to be run when the option name specified is @@ -575,7 +576,7 @@ def field_for(name, options) end def field_type_klass_for(field, type) - klass = Mongoid::FieldTypes.get(type) + klass = Fields::FieldTypes.get(type) return klass if klass raise Mongoid::Errors::InvalidFieldType.new(self.name, field, type) end diff --git a/lib/mongoid/fields/field_types.rb b/lib/mongoid/fields/field_types.rb new file mode 100644 index 0000000000..ae747842ae --- /dev/null +++ b/lib/mongoid/fields/field_types.rb @@ -0,0 +1,69 @@ +# frozen_string_literal: true + +module Mongoid + module Fields + + # Singleton module which contains a cache for field type definitions. + # Custom field types can be configured. + module FieldTypes + extend self + + # For fields defined with symbols use the correct class. + DEFAULT_MAPPING = { + array: Array, + bigdecimal: BigDecimal, + big_decimal: BigDecimal, + binary: BSON::Binary, + boolean: Mongoid::Boolean, + date: Date, + datetime: DateTime, + date_time: DateTime, + decimal128: BSON::Decimal128, + double: Float, + float: Float, + hash: Hash, + integer: Integer, + object: Object, + object_id: BSON::ObjectId, + range: Range, + regexp: Regexp, + set: Set, + string: String, + stringified_symbol: Mongoid::StringifiedSymbol, + symbol: Symbol, + time: Time, + time_with_zone: ActiveSupport::TimeWithZone + }.with_indifferent_access.freeze + + def get(value) + mapping[value] || handle_unmapped_type(value) + end + + def define(symbol, klass) + mapping[symbol] = klass + end + + delegate :delete, to: :mapping + + def mapping + @mapping ||= DEFAULT_MAPPING.dup + end + + def handle_unmapped_type(type) + return Object if type.nil? + + if type.is_a?(Module) + symbol = type.name.demodulize.underscore + Mongoid.logger.warn( + "Using a Class (#{type}) as the field :type option is deprecated and will be removed in Mongoid 8.0. " + + "Please use a Symbol (:#{symbol}) instead." + ) + return Mongoid::Boolean if type.to_s == 'Boolean' + return type + end + + nil + end + end + end +end diff --git a/spec/mongoid/errors/invalid_field_type_spec.rb b/spec/mongoid/errors/invalid_field_type_spec.rb new file mode 100644 index 0000000000..97aec11bdb --- /dev/null +++ b/spec/mongoid/errors/invalid_field_type_spec.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require "spec_helper" + +describe Mongoid::Errors::InvalidFieldType do + + describe "#message" do + + let(:error) do + described_class.new(Person, :first_name, :stringgy) + end + + it "contains the problem in the message" do + expect(error.message).to include( + "Invalid field type :stringgy for field :first_name on model 'Person'." + ) + end + + it "contains the summary in the message" do + expect(error.message).to include( + "Model 'Person' defines a field :first_name with an unknown :type value :stringgy." + ) + end + + it "contains the resolution in the message" do + expect(error.message).to include( + 'Please provide a valid :type value for the field. If you meant to define' + ) + end + end +end From b231317d396a3797958fe0cf10f090a44f833707 Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 23:15:30 +0900 Subject: [PATCH 08/14] Fix broken spec --- lib/mongoid/fields.rb | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index 48107a9738..94387681ec 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -12,6 +12,10 @@ module Mongoid module Fields extend ActiveSupport::Concern + # @deprecated Remove class aliases in Mongoid 8.0. + StringifiedSymbol = Mongoid::StringifiedSymbol + Boolean = Mongoid::Boolean + # Constant for all names of the _id field in a document. # # This does not include aliases of _id field. From fba73df07c37259b9ae20d16d4d09d737b8de47a Mon Sep 17 00:00:00 2001 From: shields Date: Sat, 1 Jan 2022 23:56:48 +0900 Subject: [PATCH 09/14] Remove usages of field :type as a Class; convert to Symbol everywhere it makes sense to do so. --- CHANGELOG.md | 26 +++--- docs/reference/associations.txt | 59 +++++++------- docs/reference/callbacks.txt | 8 +- docs/reference/crud.txt | 10 +-- docs/reference/fields.txt | 69 ++++++++-------- docs/reference/indexes.txt | 2 +- docs/reference/inheritance.txt | 54 ++++++------- docs/reference/queries.txt | 80 +++++++++---------- docs/reference/text-search.txt | 4 +- docs/release-notes/mongoid-7.2.txt | 4 +- docs/release-notes/mongoid-7.3.txt | 14 +--- docs/release-notes/mongoid-7.5.txt | 2 +- docs/tutorials/getting-started-rails.txt | 12 +-- docs/tutorials/getting-started-sinatra.txt | 8 +- .../association/referenced/belongs_to.rb | 2 +- lib/mongoid/attributes/readonly.rb | 4 +- lib/mongoid/fields.rb | 2 +- lib/mongoid/fields/field_types.rb | 5 +- lib/mongoid/indexable.rb | 2 +- lib/mongoid/scopable.rb | 10 +-- lib/mongoid/timestamps/created.rb | 2 +- lib/mongoid/timestamps/created/short.rb | 2 +- lib/mongoid/timestamps/updated.rb | 2 +- lib/mongoid/timestamps/updated/short.rb | 2 +- lib/mongoid/traversable.rb | 4 +- lib/mongoid/validatable/uniqueness.rb | 2 +- .../associations/foreign_key_spec_models.rb | 16 ++-- .../reverse_population_spec_models.rb | 4 +- spec/integration/callbacks_models.rb | 6 +- spec/integration/discriminator_key_spec.rb | 30 +++---- spec/mongoid/association/auto_save_spec.rb | 2 +- .../mongoid/association/constrainable_spec.rb | 2 +- .../association/embedded/cyclic_spec.rb | 2 +- .../embedded/embeds_many/proxy_spec.rb | 6 +- .../embedded/embeds_many_models.rb | 14 ++-- .../association/embedded/embeds_one_models.rb | 6 +- .../has_and_belongs_to_many/proxy_spec.rb | 4 +- .../has_and_belongs_to_many_models.rb | 20 ++--- .../association/referenced/has_many_models.rb | 20 ++--- .../association/referenced/has_one_models.rb | 10 +-- spec/mongoid/association_spec.rb | 2 +- spec/mongoid/attributes_spec.rb | 8 +- spec/mongoid/copyable_spec_models.rb | 4 +- spec/mongoid/criteria/findable_spec.rb | 12 +-- spec/mongoid/document_spec.rb | 2 +- spec/mongoid/fields/foreign_key_spec.rb | 44 +++++----- spec/mongoid/fields/localized_spec.rb | 24 +++--- spec/mongoid/fields/standard_spec.rb | 10 +-- spec/mongoid/fields_spec.rb | 18 ++--- spec/mongoid/shardable_models.rb | 4 +- spec/mongoid/touchable_spec_models.rb | 2 +- spec/mongoid/traversable_spec.rb | 2 +- spec/mongoid/validatable/numericality_spec.rb | 2 +- spec/support/models/account.rb | 16 ++-- spec/support/models/actor.rb | 2 +- spec/support/models/address.rb | 24 +++--- spec/support/models/address_component.rb | 2 +- spec/support/models/address_number.rb | 2 +- spec/support/models/agent.rb | 6 +- spec/support/models/alert.rb | 2 +- spec/support/models/animal.rb | 8 +- spec/support/models/answer.rb | 2 +- spec/support/models/appointment.rb | 4 +- spec/support/models/array_field.rb | 2 +- spec/support/models/article.rb | 10 +-- spec/support/models/artist.rb | 2 +- spec/support/models/audio.rb | 2 +- spec/support/models/author.rb | 6 +- spec/support/models/band.rb | 32 ++++---- spec/support/models/bar.rb | 4 +- spec/support/models/birthday.rb | 2 +- spec/support/models/book.rb | 4 +- spec/support/models/browser.rb | 2 +- spec/support/models/building_address.rb | 2 +- spec/support/models/bus.rb | 6 +- spec/support/models/business.rb | 2 +- spec/support/models/canvas.rb | 4 +- spec/support/models/church.rb | 4 +- spec/support/models/circle.rb | 2 +- spec/support/models/code.rb | 2 +- spec/support/models/coding/pull_request.rb | 2 +- spec/support/models/comment.rb | 4 +- spec/support/models/consumption_period.rb | 2 +- spec/support/models/contractor.rb | 2 +- spec/support/models/country_code.rb | 4 +- spec/support/models/customer_address.rb | 6 +- spec/support/models/deed.rb | 2 +- spec/support/models/definition.rb | 10 +-- spec/support/models/dictionary.rb | 14 ++-- spec/support/models/division.rb | 2 +- spec/support/models/dog.rb | 2 +- spec/support/models/drug.rb | 4 +- spec/support/models/entry.rb | 4 +- spec/support/models/event.rb | 2 +- spec/support/models/exhibitor.rb | 2 +- spec/support/models/eye.rb | 2 +- spec/support/models/fire_hydrant.rb | 2 +- spec/support/models/folder.rb | 2 +- spec/support/models/folder_item.rb | 2 +- spec/support/models/game.rb | 4 +- spec/support/models/ghost.rb | 2 +- spec/support/models/house.rb | 4 +- spec/support/models/idnodef.rb | 2 +- spec/support/models/implant.rb | 2 +- spec/support/models/item.rb | 6 +- spec/support/models/jar.rb | 2 +- spec/support/models/kaleidoscope.rb | 2 +- spec/support/models/label.rb | 12 +-- spec/support/models/language.rb | 2 +- spec/support/models/league.rb | 2 +- spec/support/models/location.rb | 6 +- spec/support/models/login.rb | 6 +- spec/support/models/manufacturer.rb | 2 +- spec/support/models/message.rb | 4 +- spec/support/models/mop.rb | 22 ++--- spec/support/models/movie.rb | 2 +- spec/support/models/name.rb | 10 +-- spec/support/models/name_only.rb | 2 +- spec/support/models/note.rb | 4 +- spec/support/models/order.rb | 2 +- spec/support/models/ordered_post.rb | 4 +- spec/support/models/ordered_preference.rb | 4 +- spec/support/models/oscar.rb | 4 +- spec/support/models/parent_doc.rb | 2 +- spec/support/models/passport.rb | 6 +- spec/support/models/patient.rb | 2 +- spec/support/models/person.rb | 50 ++++++------ spec/support/models/pet.rb | 2 +- spec/support/models/phone.rb | 4 +- spec/support/models/pizza.rb | 2 +- spec/support/models/player.rb | 8 +- spec/support/models/post.rb | 8 +- spec/support/models/post_genre.rb | 2 +- spec/support/models/preference.rb | 6 +- spec/support/models/princess.rb | 2 +- spec/support/models/product.rb | 4 +- spec/support/models/profile.rb | 4 +- spec/support/models/pronunciation.rb | 2 +- spec/support/models/pub.rb | 2 +- .../models/publication/encyclopedia.rb | 2 +- spec/support/models/quiz.rb | 4 +- spec/support/models/rating.rb | 2 +- spec/support/models/record.rb | 16 ++-- spec/support/models/registry.rb | 2 +- spec/support/models/role.rb | 2 +- spec/support/models/sandwich.rb | 2 +- spec/support/models/scribe.rb | 2 +- spec/support/models/seat.rb | 2 +- spec/support/models/seo.rb | 2 +- spec/support/models/server.rb | 4 +- spec/support/models/service.rb | 6 +- spec/support/models/shape.rb | 4 +- spec/support/models/shelf.rb | 2 +- spec/support/models/shirt.rb | 4 +- spec/support/models/shop.rb | 2 +- spec/support/models/short_quiz.rb | 2 +- spec/support/models/simple.rb | 2 +- spec/support/models/sound.rb | 2 +- spec/support/models/square.rb | 4 +- spec/support/models/staff.rb | 2 +- spec/support/models/subscription.rb | 2 +- spec/support/models/symptom.rb | 2 +- spec/support/models/tag.rb | 2 +- spec/support/models/target.rb | 2 +- spec/support/models/template.rb | 2 +- spec/support/models/topping.rb | 2 +- spec/support/models/track.rb | 12 +-- spec/support/models/tree.rb | 2 +- spec/support/models/truck.rb | 2 +- spec/support/models/updatable.rb | 2 +- spec/support/models/user.rb | 4 +- spec/support/models/user_account.rb | 6 +- spec/support/models/validation_callback.rb | 2 +- spec/support/models/version.rb | 2 +- spec/support/models/vet_visit.rb | 2 +- spec/support/models/video.rb | 8 +- spec/support/models/wiki_page.rb | 8 +- spec/support/models/word.rb | 4 +- spec/support/models/word_origin.rb | 8 +- spec/support/models/writer.rb | 2 +- 180 files changed, 628 insertions(+), 629 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c37f774fb5..27d41073b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -750,7 +750,7 @@ child elements. class Person include Mongoid::Document - field :username, type: String + field :username, type: :string has_many :cats, primary_key: "username" end @@ -877,7 +877,7 @@ child elements. class Event include Mongoid::Document - field :created_at, type: DateTime + field :created_at, type: :date_time index({ created_at: 1 }, { expire_after_seconds: 3600 }) end @@ -1698,7 +1698,7 @@ child elements. class Band include Mongoid::Document - field :name, type: String + field :name, type: :string end Band.attribute_names @@ -1718,7 +1718,7 @@ child elements. class User include Mongoid::Document - field :name, type: String + field :name, type: :string embeds_many :prefs, class_name: "Preference", store_as: 'my_preferences' end @@ -1750,7 +1750,7 @@ child elements. class Band include Mongoid::Document - field :name, type: String, default: "New" + field :name, type: :string, default: "New" end band = Band.first @@ -1811,7 +1811,7 @@ child elements. class Rule include Mongoid::Document - field :pattern, type: Regexp, default: /[^abc]/ + field :pattern, type: :regexp, default: /[^abc]/ end * \#1714/\#1706 Added better logging on index creation. (Hans Hasselberg) @@ -2069,7 +2069,7 @@ child elements. class Person include Mongoid::Document - field :title, type: String + field :title, type: :string end Person.new.age = 50 # raises the UnknownAttribute error. @@ -2079,8 +2079,8 @@ child elements. class Band include Mongoid::Document - field :name, type: String - field :genre, type: String + field :name, type: :string + field :genre, type: :string attr_readonly :name, :genre end @@ -2114,7 +2114,7 @@ child elements. class Band include Mongoid::Document - field :name, type: String + field :name, type: :string index({ name: 1 }, { unique: true, background: true }) end @@ -2123,7 +2123,7 @@ child elements. class Venue include Mongoid::Document - field :location, type: Array + field :location, type: :array index location: "2d" end @@ -2202,7 +2202,7 @@ child elements. class Band include Mongoid::Document - field :_id, type: String, default: ->{ name } + field :_id, type: :string, default: ->{ name } end To have the default applied *before* other attributes, set `:pre_processed` @@ -2211,7 +2211,7 @@ child elements. class Band include Mongoid::Document field :_id, - type: String, + type: :string, pre_processed: true, default: ->{ BSON::ObjectId.new.to_s } end diff --git a/docs/reference/associations.txt b/docs/reference/associations.txt index 79ded3e26f..e33bd954de 100644 --- a/docs/reference/associations.txt +++ b/docs/reference/associations.txt @@ -348,7 +348,7 @@ For example, given the following models: has_many :tours has_many :awards - field :name, type: String + field :name, type: :string end class Tour @@ -356,7 +356,7 @@ For example, given the following models: belongs_to :band - field :year, type: Integer + field :year, type: :integer end class Award @@ -364,7 +364,7 @@ For example, given the following models: belongs_to :band - field :name, type: String + field :name, type: :string end One could retrieve all bands that have toured since 2000 as follows: @@ -418,7 +418,7 @@ in order for it to work properly. class Label include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :band end @@ -472,7 +472,7 @@ the association in order for it to work properly. class Album include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :band end @@ -515,7 +515,7 @@ children via ``parent_`` and ``child_`` methods. class Tag include Mongoid::Document - field :name, type: String + field :name, type: :string recursively_embeds_many end @@ -567,13 +567,13 @@ help of MongoDB projection operation: class Band include Mongoid::Document - field :started_on, type: Date + field :started_on, type: :date embeds_one :label end class Label include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :band end @@ -599,19 +599,19 @@ following models: include Mongoid::Document embeds_many :tours embeds_many :awards - field :name, type: String + field :name, type: :string end class Tour include Mongoid::Document embedded_in :band - field :year, type: Integer + field :year, type: :integer end class Award include Mongoid::Document embedded_in :band - field :name, type: String + field :name, type: :string end To retrieve bands based on tour attributes, use the dot notation as follows: @@ -734,7 +734,7 @@ and remove the default value: embedded_in :order - field :_id, type: Object + field :_id, type: :object end In the current version of Mongoid the field definition is required, but @@ -893,16 +893,19 @@ association: class Company include Mongoid::Document - field :c, type: String + field :c, type: :string has_many :emails, foreign_key: 'c_ref', primary_key: 'c' end class Email include Mongoid::Document + # This definition of c_ref is automatically generated by Mongoid: - # field :c_ref, type: Object + # field :c_ref, type: :object + # But the type can also be specified: - field :c_ref, type: String + field :c_ref, type: :string + belongs_to :company, foreign_key: 'c_ref', primary_key: 'c' end @@ -930,8 +933,8 @@ An example might make this more clear: class Company include Mongoid::Document - field :c_id, type: Integer - field :e_ids, type: Array + field :c_id, type: :integer + field :e_ids, type: :array has_and_belongs_to_many :employees, primary_key: :e_id, foreign_key: :e_ids, @@ -941,8 +944,8 @@ An example might make this more clear: class Employee include Mongoid::Document - field :e_id, type: Integer - field :c_ids, type: Array + field :e_id, type: :integer + field :c_ids, type: :array has_and_belongs_to_many :companies, primary_key: :c_id, foreign_key: :c_ids, @@ -1095,7 +1098,7 @@ polymorphic association: class Product include Mongoid::Document - field :name, type: String + field :name, type: :string has_and_belongs_to_many :bundles embeds_many :prices, as: :item @@ -1104,7 +1107,7 @@ polymorphic association: class Bundle include Mongoid::Document - field :name, type: String + field :name, type: :string has_and_belongs_to_many :products embeds_many :prices, as: :item @@ -1289,7 +1292,7 @@ be touched on the parent association in addition to updated_at: class Label include Mongoid::Document include Mongoid::Timestamps - field :bands_updated_at, type: Time + field :bands_updated_at, type: :time has_many :bands end @@ -1524,19 +1527,19 @@ referenced associations: include Mongoid::Document has_many :tours has_many :awards - field :name, type: String + field :name, type: :string end class Tour include Mongoid::Document belongs_to :band - field :year, type: Integer + field :year, type: :integer end class Award include Mongoid::Document belongs_to :band - field :name, type: String + field :name, type: :string end To retrieve bands that toured since 2000 and have at least one award, one @@ -1600,8 +1603,8 @@ For example, given the following models: embeds_many :participants - field :name, type: String - field :states, type: Array + field :name, type: :string + field :states, type: :array end class Participant @@ -1609,7 +1612,7 @@ For example, given the following models: embedded_in :tour - field :name, type: String + field :name, type: :string end We could find out which states a participant visited: diff --git a/docs/reference/callbacks.txt b/docs/reference/callbacks.txt index f6d1e70d1e..4e3aecbac1 100644 --- a/docs/reference/callbacks.txt +++ b/docs/reference/callbacks.txt @@ -52,9 +52,9 @@ for cross-cutting concerns, like queueing up background jobs. class Article include Mongoid::Document - field :name, type: String - field :body, type: String - field :slug, type: String + field :name, type: :string + field :body, type: :string + field :slug, type: :string before_create :send_message @@ -75,7 +75,7 @@ syntax as well: class Article include Mongoid::Document - field :name, type: String + field :name, type: :string set_callback(:create, :before) do |document| # Message sending code here. diff --git a/docs/reference/crud.txt b/docs/reference/crud.txt index 0a3911f291..ad34bf3bc2 100644 --- a/docs/reference/crud.txt +++ b/docs/reference/crud.txt @@ -425,7 +425,7 @@ are not invoked. class Post include Mongoid::Document - field :metadata, type: Hash + field :metadata, type: :hash end post = Post.create! @@ -447,7 +447,7 @@ are not invoked. embedded_in :flight - field :route, type: String + field :route, type: :string end flight = Flight.create! @@ -777,7 +777,7 @@ the database up to the time it is saved. Any persistence operation clears the ch class Person include Mongoid::Document - field :name, type: String + field :name, type: :string end person = Person.first @@ -857,7 +857,7 @@ For example, adding to a set like this does not work: class Band include Mongoid::Document - field :tours, type: Set + field :tours, type: :set end band = Band.new @@ -877,7 +877,7 @@ back to the model as follows: class Band include Mongoid::Document - field :tours, type: Set + field :tours, type: :set end band = Band.new diff --git a/docs/reference/fields.txt b/docs/reference/fields.txt index caf9d1d1e8..15188dfd3b 100644 --- a/docs/reference/fields.txt +++ b/docs/reference/fields.txt @@ -84,9 +84,10 @@ Below is a list of valid types for fields. To define custom field types, refer to :ref:`Custom Field Types ` below. -As of Mongoid 7.5, ``field :type`` should be specified as a ``Symbol``. -Specifying as a ``Class`` is deprecated and will be no longer supported in Mongoid 8.0. -Unrecognized field type symbols will result in an `InvalidFieldType` error when the model class is loaded. +As of Mongoid 7.5, the ``field :type`` option should be specified as a ``Symbol`` value +(e.g. ``type: :float``). Specifying as a ``Class`` (e.g. ``type: Float``) is deprecated +and will be no longer supported in Mongoid 8.0. Unrecognized field type symbols will result +in an `InvalidFieldType` error when the model class is loaded. .. _omitting-field-type-definition: @@ -141,7 +142,7 @@ An example usage is shown below: class Post include Mongoid::Document - field :status, type: StringifiedSymbol + field :status, type: :stringified_symbol end post = Post.new(status: :hello) @@ -168,10 +169,10 @@ For example, setting an integer as ``status``: post.status # => :"42" -If the ``StringifiedSymbol`` type is applied to a field that contains BSON symbols, the values +If the ``:stringified_symbol`` type is applied to a field that contains BSON symbols, the values will be stored as strings instead of BSON symbols on the next save. This permits transparent lazy migration from fields that currently store either strings or BSON symbols in the database to the -``StringifiedSymbol`` field type. +``:stringified_symbol`` field type. .. _field-type-symbol: @@ -186,9 +187,9 @@ and has the same behavior in all circumstances. Mongoid also provides the deprecated ``:symbol`` field type for serializing Ruby symbols to BSON symbols. Because the BSON specification deprecated the -BSON symbol type, the `bson` gem will serialize Ruby symbols into BSON strings +BSON symbol type, the ``bson`` gem will serialize Ruby symbols into BSON strings when used on its own. However, in order to maintain backwards compatibility -with older datasets, the `mongo` gem overrides this behavior to serialize Ruby +with older datasets, the ``mongo`` gem overrides this behavior to serialize Ruby symbols as BSON symbols. This is necessary to be able to specify queries for documents which contain BSON symbols as fields. @@ -435,7 +436,7 @@ fixed, as in the following example: class Order include Mongoid::Document - field :state, type: String, default: 'created' + field :state, type: :string, default: 'created' end The default value can also be specified as a ``Proc``: @@ -445,7 +446,7 @@ The default value can also be specified as a ``Proc``: class Order include Mongoid::Document - field :fulfill_by, type: Time, default: ->{ Time.now + 3.days } + field :fulfill_by, type: :time, default: ->{ Time.now + 3.days } end .. note:: @@ -455,8 +456,8 @@ The default value can also be specified as a ``Proc``: .. code-block:: ruby - field :submitted_at, type: Time, default: Time.now - field :submitted_at, type: Time, default: ->{ Time.now } + field :submitted_at, type: :time, default: Time.now + field :submitted_at, type: :time, default: ->{ Time.now } The second definition is most likely the desired one, which causes the time of submission to be set to the current time at the moment of @@ -468,7 +469,7 @@ being operated on: .. code-block:: ruby - field :fulfill_by, type: Time, default: ->{ + field :fulfill_by, type: :time, default: ->{ # Order should be fulfilled in 2 business hours. if (7..8).include?(self.submitted_at.hour) self.submitted_at + 4.hours @@ -485,7 +486,7 @@ the other attributes are set, use the ``pre_processed: true`` field option: .. code-block:: ruby - field :fulfill_by, type: Time, default: ->{ Time.now + 3.days }, + field :fulfill_by, type: :time, default: ->{ Time.now + 3.days }, pre_processed: true @@ -506,7 +507,7 @@ and criteria while performing the conversion for you. class Band include Mongoid::Document - field :n, as: :name, type: String + field :n, as: :name, type: :string end band = Band.new(name: "Placebo") @@ -530,7 +531,7 @@ from the aliased field: class Band include Mongoid::Document - field :name, type: String + field :name, type: :string alias_attribute :n, :name end @@ -566,7 +567,7 @@ This is useful for storing different values in ``id`` and ``_id`` fields: include Mongoid::Document unalias_attribute :id - field :id, type: String + field :id, type: :string end Band.new(id: '42') @@ -597,7 +598,7 @@ With the option set to true, the following example will raise an error: field :name - field :name, type: String + field :name, type: :string end To define the field anyway, use the ``overwrite: true`` option: @@ -609,7 +610,7 @@ To define the field anyway, use the ``overwrite: true`` option: field :name - field :name, type: String, overwrite: true + field :name, type: :string, overwrite: true end @@ -628,8 +629,8 @@ of the ``_id`` values or have different default values: class Band include Mongoid::Document - field :name, type: String - field :_id, type: String, default: ->{ name } + field :name, type: :string + field :_id, type: :string, default: ->{ name } end It is possible to omit the default entirely: @@ -638,7 +639,7 @@ It is possible to omit the default entirely: class Band include Mongoid::Document - field :_id, type: String + field :_id, type: :string end If the default on ``_id`` is omitted, and no ``_id`` value is provided by @@ -697,8 +698,8 @@ getter as follows: class DistanceMeasurement include Mongoid::Document - field :value, type: Float - field :unit, type: String + field :value, type: :float + field :unit, type: :string def unit read_attribute(:unit) || "m" @@ -723,8 +724,8 @@ may be implemented as follows: class DistanceMeasurement include Mongoid::Document - field :value, type: Float - field :unit, type: String + field :value, type: :float + field :unit, type: :string def unit=(value) if value.blank? @@ -745,8 +746,8 @@ Custom Field Types ------------------ You can define custom types in Mongoid and determine how they are serialized -and deserialized. In this example, we define a new field type ``Point``, which we -can use in our model class as follows: +and deserialized. In this example, we define a new field type ``:point``, +which we can use in our model class as follows: .. code-block:: ruby @@ -766,8 +767,9 @@ First, declare the new field type mapping in an initializer: end -Then make a Ruby class to represent the type. This class must define methods -used for MongoDB serialization and deserialization as follows: +Then make a Ruby class ``Point`` to represent the type. +This class must define methods used for MongoDB serialization +and deserialization as follows: .. code-block:: ruby @@ -874,7 +876,7 @@ Then, use it your model class: class Person include Mongoid::Document - field :name, type: String, required: true + field :name, type: :string, required: true end Note that the handler function will be invoked whenever the option is used @@ -1127,6 +1129,7 @@ alter the criteria to match the current locale. Product.where(description: "Marvelous!") # The resulting MongoDB query filter: { "description.en" : "Marvelous!" } + Indexing -------- @@ -1157,8 +1160,8 @@ ignored when using mass update methods such as ``update_attributes``: class Band include Mongoid::Document - field :name, type: String - field :origin, type: String + field :name, type: :string + field :origin, type: :string attr_readonly :name, :origin end diff --git a/docs/reference/indexes.txt b/docs/reference/indexes.txt index 73fd691ec4..602b4bc777 100644 --- a/docs/reference/indexes.txt +++ b/docs/reference/indexes.txt @@ -97,7 +97,7 @@ For geospatial indexes, make sure the field being indexed is of type Array: class Person include Mongoid::Document - field :location, type: Array + field :location, type: :array index({ location: "2d" }, { min: -200, max: 200 }) end diff --git a/docs/reference/inheritance.txt b/docs/reference/inheritance.txt index f1fde10526..be1d971828 100644 --- a/docs/reference/inheritance.txt +++ b/docs/reference/inheritance.txt @@ -20,12 +20,12 @@ fields, associations, validations and scopes are copied to the child document. class Canvas include Mongoid::Document - field :name, type: String + field :name, type: :string embeds_many :shapes end class Browser < Canvas - field :version, type: Integer + field :version, type: :integer scope :recent, ->{ where(:version.gt => 3) } end @@ -34,18 +34,18 @@ fields, associations, validations and scopes are copied to the child document. class Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas end class Circle < Shape - field :radius, type: Float + field :radius, type: :float end class Rectangle < Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end In the above example, ``Canvas``, ``Browser`` and ``Firefox`` will all save in the canvases @@ -87,20 +87,20 @@ Take the above example: class Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas self.discriminator_key = "shape_type" end class Circle < Shape - field :radius, type: Float + field :radius, type: :float end class Rectangle < Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end Here a call to the ``discriminator_key=`` setter was added to the parent class. Now, on @@ -117,18 +117,18 @@ For example: class Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas end class Circle < Shape - field :radius, type: Float + field :radius, type: :float end class Rectangle < Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end Shape.discriminator_key = "shape_type" @@ -146,18 +146,18 @@ use the globally set discriminator key instead of ``_type``. Take the above exam class Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas end class Circle < Shape - field :radius, type: Float + field :radius, type: :float end class Rectangle < Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end After setting the global discriminator key, all classes will use ``_the_type`` as @@ -184,20 +184,20 @@ Take the above example: class Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas end class Circle < Shape - field :radius, type: Float + field :radius, type: :float self.discriminator_value = "round thing" end class Rectangle < Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end Here, a call to the ``discriminator_value=`` setter was added to ``Circle``. diff --git a/docs/reference/queries.txt b/docs/reference/queries.txt index a62039e29f..42988380ac 100644 --- a/docs/reference/queries.txt +++ b/docs/reference/queries.txt @@ -101,9 +101,9 @@ The examples in this section use the following model definition: class Band include Mongoid::Document - field :name, type: String - field :founded, type: Integer - field :m, as: :member_count, type: Integer + field :name, type: :string + field :founded, type: :integer + field :m, as: :member_count, type: :integer embeds_one :manager end @@ -113,7 +113,7 @@ The examples in this section use the following model definition: embedded_in :band - field :name, type: String + field :name, type: :string end Field Syntax @@ -664,8 +664,8 @@ matches all of the conditions. For example: class Band include Mongoid::Document - field :name, type: String - field :tours, type: Array + field :name, type: :string + field :tours, type: :array end aerosmith = Band.create!(name: 'Aerosmith', tours: [ @@ -681,14 +681,14 @@ matches all of the conditions. For example: class Band include Mongoid::Document - field :name, type: String + field :name, type: :string embeds_many :tours end class Tour include Mongoid::Document - field :city, type: String - field :year, type: Integer + field :city, type: :string + field :year, type: :integer embedded_in :band end @@ -711,7 +711,7 @@ as the following example shows: class Tag include Mongoid::Document - field :name, type: String + field :name, type: :string recursively_embeds_many end @@ -747,8 +747,8 @@ operation is sometimes called "projection". class Band include Mongoid::Document - field :name, type: String - field :label, type: String + field :name, type: :string + field :label, type: :string embeds_many :tours end @@ -756,8 +756,8 @@ operation is sometimes called "projection". class Tour include Mongoid::Document - field :city, type: String - field :year, type: Integer + field :city, type: :string + field :year, type: :integer embedded_in :band end @@ -820,7 +820,7 @@ loaded with ``only`` for those associations to be loaded. For example: class Band include Mongoid::Document - field :name, type: String + field :name, type: :string has_and_belongs_to_many :managers end @@ -975,8 +975,8 @@ the default scope being evaluated first: class Band include Mongoid::Document - field :name, type: String - field :year, type: Integer + field :name, type: :string + field :year, type: :integer default_scope -> { order(name: :asc) } end @@ -1176,7 +1176,7 @@ Mongoid also has some helpful methods on criteria. class Contract include Mongoid::Document - field :active, type: Boolean + field :active, type: :boolean default_scope -> { where(active: true) } end @@ -1419,8 +1419,8 @@ Given the following model definitions: class Band include Mongoid::Document - field :name, type: String - field :description, type: String + field :name, type: :string + field :description, type: :string end Band.create!(name: 'Sun Project', description: "Sun\nProject") @@ -1461,8 +1461,8 @@ intentionally does not define a field called ``deregistered_at``: class Voter include Mongoid::Document - field :born_on, type: Date - field :registered_at, type: Time + field :born_on, type: :date + field :registered_at, type: :time field :voted_at end @@ -1523,8 +1523,8 @@ by a provided name. Just like normal criteria, they are lazy and chainable. class Band include Mongoid::Document - field :country, type: String - field :genres, type: Array + field :country, type: :string + field :genres, type: :array scope :english, ->{ where(country: "England") } scope :rock, ->{ where(:genres.in => [ "rock" ]) } @@ -1539,9 +1539,9 @@ extending functionality. class Band include Mongoid::Document - field :name, type: String - field :country, type: String - field :active, type: Boolean, default: true + field :name, type: :string + field :country, type: :string + field :active, type: :boolean, default: true scope :named, ->(name){ where(name: name) } scope :active, ->{ @@ -1588,8 +1588,8 @@ Default scopes are procs that return criteria objects. class Band include Mongoid::Document - field :name, type: String - field :active, type: Boolean + field :name, type: :string + field :active, type: :boolean default_scope ->{ where(active: true) } end @@ -1605,9 +1605,9 @@ the values given in the default scope, if the values are simple literals: class Band include Mongoid::Document - field :name, type: String - field :active, type: Boolean - field :num_tours, type: Integer + field :name, type: :string + field :active, type: :boolean + field :num_tours, type: :integer default_scope ->{ where(active: true, num_tours: {'$gt' => 1}) } end @@ -1622,8 +1622,8 @@ in the default scope, the value in the default scope takes precedence: class Band include Mongoid::Document - field :name, type: String - field :active, type: Boolean, default: true + field :name, type: :string + field :active, type: :boolean, default: true default_scope ->{ where(active: false) } end @@ -1638,8 +1638,8 @@ not possible: class Band include Mongoid::Document - field :name, type: String - field :tags, type: Hash + field :name, type: :string + field :tags, type: :hash default_scope ->{ where('tags.foo' => 'bar') } end @@ -1652,8 +1652,8 @@ A workaround is to define the default scope as a complex query: class Band include Mongoid::Document - field :name, type: String - field :tags, type: Hash + field :name, type: :string + field :tags, type: :hash default_scope ->{ where('tags.foo' => {'$eq' => 'bar'}) } end @@ -1715,8 +1715,8 @@ treated like scopes, and can be chained as well. class Band include Mongoid::Document - field :name, type: String - field :active, type: Boolean, default: true + field :name, type: :string + field :active, type: :boolean, default: true def self.active where(active: true) diff --git a/docs/reference/text-search.txt b/docs/reference/text-search.txt index a7a994c173..66e71545db 100644 --- a/docs/reference/text-search.txt +++ b/docs/reference/text-search.txt @@ -46,8 +46,8 @@ a text index utilizing the description field: class Band include Mongoid::Document - field :name, type: String - field :description, type: String + field :name, type: :string + field :description, type: :string index description: 'text' end diff --git a/docs/release-notes/mongoid-7.2.txt b/docs/release-notes/mongoid-7.2.txt index c01cf36f46..38b2c014ed 100644 --- a/docs/release-notes/mongoid-7.2.txt +++ b/docs/release-notes/mongoid-7.2.txt @@ -345,7 +345,7 @@ Consider a class ``Band`` whose documents are sharded by the ``name`` key. class Band include Mongoid::Document - field :name, type: String + field :name, type: :string shard_key :name end @@ -425,7 +425,7 @@ Example Mongoid 7.2 behavior: class Offer include Mongoid::Document - field :constraint, type: Regexp + field :constraint, type: :regexp end offer = Offer.create!(constraint: /foo/) diff --git a/docs/release-notes/mongoid-7.3.txt b/docs/release-notes/mongoid-7.3.txt index ee103b1d9e..4af1ac4633 100644 --- a/docs/release-notes/mongoid-7.3.txt +++ b/docs/release-notes/mongoid-7.3.txt @@ -90,21 +90,11 @@ unqualified: User.field :verified, type: Boolean -To fix it, use the fully-qualified ``Mongoid::Boolean`` class: +To fix it, use ``:boolean`` as a Symbol: .. code-block:: ruby - User.field :verified, type: Mongoid::Boolean - -Note that ``class_eval`` is executed in the scope of the caller, not in -the scope of the class being modified. Thus even when using ``class_eval`` -it is necessary to fully qualify ``Mongoid::Boolean``: - -.. code-block:: ruby - - User.class_eval do - field :verified, type: Mongoid::Boolean - end + User.field :verified, type: :boolean Additionally, in Mongoid 7.2 ``::Boolean`` and ``Mongoid::Boolean`` were different classes. In Mongoid 7.3 there is only one class which is diff --git a/docs/release-notes/mongoid-7.5.txt b/docs/release-notes/mongoid-7.5.txt index 22906d327e..081b726dae 100644 --- a/docs/release-notes/mongoid-7.5.txt +++ b/docs/release-notes/mongoid-7.5.txt @@ -130,7 +130,7 @@ in ``after_*`` callbacks. This follows ActiveRecord/ActiveModel behavior. class Cat include Mongoid::Document - field :age, type: Integer + field :age, type: :integer after_save do p self diff --git a/docs/tutorials/getting-started-rails.txt b/docs/tutorials/getting-started-rails.txt index c5bf0bdc3b..6dc0cb84c6 100644 --- a/docs/tutorials/getting-started-rails.txt +++ b/docs/tutorials/getting-started-rails.txt @@ -248,8 +248,8 @@ association for the comments: class Post include Mongoid::Document - field :title, type: String - field :body, type: String + field :title, type: :string + field :body, type: :string has_many :comments, dependent: :destroy end @@ -264,8 +264,8 @@ generated ``embedded_in`` association to ``belongs_to``: class Comment include Mongoid::Document - field :name, type: String - field :message, type: String + field :name, type: :string + field :message, type: :string belongs_to :post end @@ -498,8 +498,8 @@ The same model may look like this in Mongoid: class Post include Mongoid::Document - field :title, type: String - field :body, type: String + field :title, type: :string + field :body, type: :string has_many :comments, dependent: :destroy end diff --git a/docs/tutorials/getting-started-sinatra.txt b/docs/tutorials/getting-started-sinatra.txt index e95f2049d7..4c542be3a5 100644 --- a/docs/tutorials/getting-started-sinatra.txt +++ b/docs/tutorials/getting-started-sinatra.txt @@ -134,8 +134,8 @@ Now we can define some models: class Post include Mongoid::Document - field :title, type: String - field :body, type: String + field :title, type: :string + field :body, type: :string has_many :comments end @@ -143,8 +143,8 @@ Now we can define some models: class Comment include Mongoid::Document - field :name, type: String - field :message, type: String + field :name, type: :string + field :message, type: :string belongs_to :post end diff --git a/lib/mongoid/association/referenced/belongs_to.rb b/lib/mongoid/association/referenced/belongs_to.rb index 046d342de0..2c914f45d2 100644 --- a/lib/mongoid/association/referenced/belongs_to.rb +++ b/lib/mongoid/association/referenced/belongs_to.rb @@ -176,7 +176,7 @@ def default_foreign_key_field def polymorph! if polymorphic? @owner_class.polymorphic = true - @owner_class.field(inverse_type, type: String) + @owner_class.field(inverse_type, type: :string) end end diff --git a/lib/mongoid/attributes/readonly.rb b/lib/mongoid/attributes/readonly.rb index 2e89e4a199..7c52a9615e 100644 --- a/lib/mongoid/attributes/readonly.rb +++ b/lib/mongoid/attributes/readonly.rb @@ -56,8 +56,8 @@ module ClassMethods # @example Flag fields as readonly. # class Band # include Mongoid::Document - # field :name, type: String - # field :genre, type: String + # field :name, type: :string + # field :genre, type: :string # attr_readonly :name, :genre # end # diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index 94387681ec..93150fa784 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -76,7 +76,7 @@ def extract_id_field(attributes) :_id, default: ->{ BSON::ObjectId.new }, pre_processed: true, - type: BSON::ObjectId + type: :object_id ) alias_attribute(:id, :_id) diff --git a/lib/mongoid/fields/field_types.rb b/lib/mongoid/fields/field_types.rb index ae747842ae..fdf33a3c22 100644 --- a/lib/mongoid/fields/field_types.rb +++ b/lib/mongoid/fields/field_types.rb @@ -32,7 +32,10 @@ module FieldTypes stringified_symbol: Mongoid::StringifiedSymbol, symbol: Symbol, time: Time, - time_with_zone: ActiveSupport::TimeWithZone + time_with_zone: ActiveSupport::TimeWithZone, + bson_regexp: BSON::Regexp::Raw, + bson_symbol: BSON::Symbol::Raw, + bson_timestamp: BSON::Timestamp }.with_indifferent_access.freeze def get(value) diff --git a/lib/mongoid/indexable.rb b/lib/mongoid/indexable.rb index d35d23504a..cd54d94eed 100644 --- a/lib/mongoid/indexable.rb +++ b/lib/mongoid/indexable.rb @@ -84,7 +84,7 @@ def add_indexes # @example Create a basic index. # class Person # include Mongoid::Document - # field :name, type: String + # field :name, type: :string # index({ name: 1 }, { background: true }) # end # diff --git a/lib/mongoid/scopable.rb b/lib/mongoid/scopable.rb index ab7c0be6ff..02c211be09 100644 --- a/lib/mongoid/scopable.rb +++ b/lib/mongoid/scopable.rb @@ -40,7 +40,7 @@ module ClassMethods # @example Get the defined scopes for a class # class Band # include Mongoid::Document - # field :active, type: Boolean + # field :active, type: :boolean # # scope :active, -> { where(active: true) } # end @@ -63,14 +63,14 @@ def scopes # @example Define a default scope with a criteria. # class Band # include Mongoid::Document - # field :active, type: Boolean + # field :active, type: :boolean # default_scope where(active: true) # end # # @example Define a default scope with a proc. # class Band # include Mongoid::Document - # field :active, type: Boolean + # field :active, type: :boolean # default_scope ->{ where(active: true) } # end # @@ -116,8 +116,8 @@ def queryable # # class Person # include Mongoid::Document - # field :active, type: Boolean - # field :count, type: Integer + # field :active, type: :boolean + # field :count, type: :integer # # scope :active, -> { where(active: true) } # scope :at_least, ->(count){ where(:count.gt => count) } diff --git a/lib/mongoid/timestamps/created.rb b/lib/mongoid/timestamps/created.rb index 8cf223899e..99ff806c2c 100644 --- a/lib/mongoid/timestamps/created.rb +++ b/lib/mongoid/timestamps/created.rb @@ -12,7 +12,7 @@ module Created included do include Mongoid::Timestamps::Timeless - field :created_at, type: Time + field :created_at, type: :time set_callback :create, :before, :set_created_at end diff --git a/lib/mongoid/timestamps/created/short.rb b/lib/mongoid/timestamps/created/short.rb index 620b377a96..e4c6b29b77 100644 --- a/lib/mongoid/timestamps/created/short.rb +++ b/lib/mongoid/timestamps/created/short.rb @@ -12,7 +12,7 @@ module Short included do include Created fields.delete("created_at") - field :c_at, type: Time, as: :created_at + field :c_at, type: :time, as: :created_at end end end diff --git a/lib/mongoid/timestamps/updated.rb b/lib/mongoid/timestamps/updated.rb index 550825d060..c2a0f516b3 100644 --- a/lib/mongoid/timestamps/updated.rb +++ b/lib/mongoid/timestamps/updated.rb @@ -12,7 +12,7 @@ module Updated included do include Mongoid::Timestamps::Timeless - field :updated_at, type: Time + field :updated_at, type: :time set_callback :create, :before, :set_updated_at set_callback :update, :before, :set_updated_at end diff --git a/lib/mongoid/timestamps/updated/short.rb b/lib/mongoid/timestamps/updated/short.rb index afaa5b4685..e80f775b4b 100644 --- a/lib/mongoid/timestamps/updated/short.rb +++ b/lib/mongoid/timestamps/updated/short.rb @@ -12,7 +12,7 @@ module Short included do include Updated fields.delete("updated_at") - field :u_at, type: Time, as: :updated_at + field :u_at, type: :time, as: :updated_at end end end diff --git a/lib/mongoid/traversable.rb b/lib/mongoid/traversable.rb index b5f5ad2d2b..b348f90180 100644 --- a/lib/mongoid/traversable.rb +++ b/lib/mongoid/traversable.rb @@ -46,7 +46,7 @@ class << self # 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) + field(self.discriminator_key, default: default_proc, type: :string) end end @@ -325,7 +325,7 @@ class << subclass # add to the root class as well for backwards compatibility. unless fields.has_key?(self.discriminator_key) default_proc = lambda { self.class.discriminator_value } - field(self.discriminator_key, default: default_proc, type: String) + field(self.discriminator_key, default: default_proc, type: :string) end end end diff --git a/lib/mongoid/validatable/uniqueness.rb b/lib/mongoid/validatable/uniqueness.rb index 594ea72c8d..278efe7d76 100644 --- a/lib/mongoid/validatable/uniqueness.rb +++ b/lib/mongoid/validatable/uniqueness.rb @@ -20,7 +20,7 @@ module Validatable # class Person # include Mongoid::Document # field :title - # field :active, type: Boolean + # field :active, type: :boolean # # validates_uniqueness_of :title, conditions: -> {where(active: true)} # end diff --git a/spec/integration/associations/foreign_key_spec_models.rb b/spec/integration/associations/foreign_key_spec_models.rb index fc22ea9c58..a10590158d 100644 --- a/spec/integration/associations/foreign_key_spec_models.rb +++ b/spec/integration/associations/foreign_key_spec_models.rb @@ -4,7 +4,7 @@ module ForeignKeySpec class Company include Mongoid::Document - field :c, type: String + field :c, type: :string has_many :emails, class_name: 'ForeignKeySpec::Email', foreign_key: 'c_ref', primary_key: 'c' has_one :founder, class_name: 'ForeignKeySpec::Founder', @@ -14,7 +14,7 @@ class Company class Email include Mongoid::Document - field :c_ref, type: String + field :c_ref, type: :string belongs_to :company, class_name: 'ForeignKeySpec::Company', foreign_key: 'c_ref', primary_key: 'c' end @@ -22,7 +22,7 @@ class Email class Founder include Mongoid::Document - field :c_ref, type: String + field :c_ref, type: :string belongs_to :company, class_name: 'ForeignKeySpec::Company', foreign_key: 'c_ref', primary_key: 'c' end @@ -30,7 +30,7 @@ class Founder class Animal include Mongoid::Document - field :a, type: String + field :a, type: :string has_and_belongs_to_many :zoos, class_name: 'ForeignKeySpec::Zoo', foreign_key: 'z_refs', primary_key: 'z' end @@ -38,7 +38,7 @@ class Animal class Zoo include Mongoid::Document - field :z, type: String + field :z, type: :string has_and_belongs_to_many :animals, class_name: 'ForeignKeySpec::Animal', foreign_key: 'a_refs', primary_key: 'a' end @@ -46,7 +46,7 @@ class Zoo class ScopedCompany include Mongoid::Document - field :c, type: String + field :c, type: :string has_many :emails, class_name: 'ForeignKeySpec::ScopedEmail', foreign_key: 'c_ref', primary_key: 'c' end @@ -54,11 +54,11 @@ class ScopedCompany class ScopedEmail include Mongoid::Document - field :c_ref, type: String + field :c_ref, type: :string belongs_to :company, class_name: 'ForeignKeySpec::ScopedCompany', foreign_key: 'c_ref', primary_key: 'c' - field :s, type: String + field :s, type: :string default_scope -> { where(s: 'on') } end end diff --git a/spec/integration/associations/reverse_population_spec_models.rb b/spec/integration/associations/reverse_population_spec_models.rb index 18113ff3b6..166df66eff 100644 --- a/spec/integration/associations/reverse_population_spec_models.rb +++ b/spec/integration/associations/reverse_population_spec_models.rb @@ -23,14 +23,14 @@ class Founder class Animal include Mongoid::Document - field :a, type: String + field :a, type: :string has_and_belongs_to_many :zoos, class_name: 'ReversePopulationSpec::Zoo' end class Zoo include Mongoid::Document - field :z, type: String + field :z, type: :string has_and_belongs_to_many :animals, class_name: 'ReversePopulationSpec::Animal' end end diff --git a/spec/integration/callbacks_models.rb b/spec/integration/callbacks_models.rb index b79a4f56aa..b97399db69 100644 --- a/spec/integration/callbacks_models.rb +++ b/spec/integration/callbacks_models.rb @@ -1,7 +1,7 @@ class Galaxy include Mongoid::Document - field :age, type: Integer + field :age, type: :integer before_validation :set_age @@ -19,7 +19,7 @@ class Star embedded_in :galaxy - field :age, type: Integer + field :age, type: :integer before_validation :set_age @@ -37,7 +37,7 @@ class Planet embedded_in :star - field :age, type: Integer + field :age, type: :integer before_validation :set_age diff --git a/spec/integration/discriminator_key_spec.rb b/spec/integration/discriminator_key_spec.rb index dccdbcdc36..aafd2121b4 100644 --- a/spec/integration/discriminator_key_spec.rb +++ b/spec/integration/discriminator_key_spec.rb @@ -210,20 +210,20 @@ class DBDiscriminatorChild < DBDiscriminatorParent before do class Example1Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas self.discriminator_key = "shape_type" end class Example1Circle < Example1Shape - field :radius, type: Float + field :radius, type: :float end class Example1Rectangle < Example1Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end end @@ -256,18 +256,18 @@ class Example1Rectangle < Example1Shape before do class Example2Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas end class Example2Circle < Example2Shape - field :radius, type: Float + field :radius, type: :float end class Example2Rectangle < Example2Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end Example2Shape.discriminator_key = "shape_type" @@ -305,18 +305,18 @@ class Example2Rectangle < Example2Shape class Example3Shape include Mongoid::Document - field :x, type: Integer - field :y, type: Integer + field :x, type: :integer + field :y, type: :integer embedded_in :canvas end class Example3Circle < Example3Shape - field :radius, type: Float + field :radius, type: :float end class Example3Rectangle < Example3Shape - field :width, type: Float - field :height, type: Float + field :width, type: :float + field :height, type: :float end end diff --git a/spec/mongoid/association/auto_save_spec.rb b/spec/mongoid/association/auto_save_spec.rb index 5f09a63e3d..98b7e2c3a6 100644 --- a/spec/mongoid/association/auto_save_spec.rb +++ b/spec/mongoid/association/auto_save_spec.rb @@ -364,7 +364,7 @@ class Peasant class Harvest include Mongoid::Document - field :season, type: String + field :season, type: :string belongs_to :peasant end end diff --git a/spec/mongoid/association/constrainable_spec.rb b/spec/mongoid/association/constrainable_spec.rb index c9d1f73307..51d376cd45 100644 --- a/spec/mongoid/association/constrainable_spec.rb +++ b/spec/mongoid/association/constrainable_spec.rb @@ -11,7 +11,7 @@ before(:all) do Person.field( :_id, - type: BSON::ObjectId, + type: :object_id, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true diff --git a/spec/mongoid/association/embedded/cyclic_spec.rb b/spec/mongoid/association/embedded/cyclic_spec.rb index 8cb9c6e389..56763d2784 100644 --- a/spec/mongoid/association/embedded/cyclic_spec.rb +++ b/spec/mongoid/association/embedded/cyclic_spec.rb @@ -62,7 +62,7 @@ class Node include Mongoid::Document recursively_embeds_many - field :name, type: String + field :name, type: :string def is_root? parent_node.nil? diff --git a/spec/mongoid/association/embedded/embeds_many/proxy_spec.rb b/spec/mongoid/association/embedded/embeds_many/proxy_spec.rb index d9098295fb..2f0203854b 100644 --- a/spec/mongoid/association/embedded/embeds_many/proxy_spec.rb +++ b/spec/mongoid/association/embedded/embeds_many/proxy_spec.rb @@ -497,9 +497,9 @@ class TrackingId class TrackingIdValidationHistory include Mongoid::Document - field :old_state, type: String - field :new_state, type: String - field :when_changed, type: DateTime + field :old_state, type: :string + field :new_state, type: :string + field :when_changed, type: :date_time embedded_in :tracking_id, class_name: "MyCompany::Model::TrackingId" end end diff --git a/spec/mongoid/association/embedded/embeds_many_models.rb b/spec/mongoid/association/embedded/embeds_many_models.rb index 71c899601b..4248c00d3b 100644 --- a/spec/mongoid/association/embedded/embeds_many_models.rb +++ b/spec/mongoid/association/embedded/embeds_many_models.rb @@ -6,7 +6,7 @@ class EmmCongress embeds_many :legislators, class_name: 'EmmLegislator' - field :name, type: String + field :name, type: :string end class EmmLegislator @@ -14,8 +14,8 @@ class EmmLegislator embedded_in :congress, class_name: 'EmmCongress' - field :a, type: Integer, default: 0 - field :b, type: Integer, default: 0 + field :a, type: :integer, default: 0 + field :b, type: :integer, default: 0 end # Models with associations with :class_name as a :: prefixed string @@ -25,7 +25,7 @@ class EmmCcCongress embeds_many :legislators, class_name: '::EmmCcLegislator' - field :name, type: String + field :name, type: :string end class EmmCcLegislator @@ -33,8 +33,8 @@ class EmmCcLegislator embedded_in :congress, class_name: '::EmmCcCongress' - field :a, type: Integer, default: 0 - field :b, type: Integer, default: 0 + field :a, type: :integer, default: 0 + field :b, type: :integer, default: 0 end class EmmManufactory @@ -49,7 +49,7 @@ class EmmProduct embedded_in :manufactory, class_name: 'EmmManufactory' - field :name, type: String + field :name, type: :string end class EmmInner diff --git a/spec/mongoid/association/embedded/embeds_one_models.rb b/spec/mongoid/association/embedded/embeds_one_models.rb index a8f31d7d7f..12e2c509b3 100644 --- a/spec/mongoid/association/embedded/embeds_one_models.rb +++ b/spec/mongoid/association/embedded/embeds_one_models.rb @@ -6,7 +6,7 @@ class EomParent embeds_one :child, class_name: 'EomChild' - field :name, type: String + field :name, type: :string end class EomChild @@ -14,8 +14,8 @@ class EomChild embedded_in :parent, class_name: 'EomParent' - field :a, type: Integer, default: 0 - field :b, type: Integer, default: 0 + field :a, type: :integer, default: 0 + field :b, type: :integer, default: 0 end # Models with associations with :class_name as a :: prefixed string diff --git a/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb b/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb index 378c440597..355f0ca196 100644 --- a/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +++ b/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb @@ -3738,7 +3738,7 @@ class Project include Mongoid::Document - field :n, type: String, as: :name + field :n, type: :string, as: :name has_and_belongs_to_many :distributors, foreign_key: :d_ids, @@ -3748,7 +3748,7 @@ class Project class Distributor include Mongoid::Document - field :n, type: String, as: :name + field :n, type: :string, as: :name has_and_belongs_to_many :projects, foreign_key: :p_ids, diff --git a/spec/mongoid/association/referenced/has_and_belongs_to_many_models.rb b/spec/mongoid/association/referenced/has_and_belongs_to_many_models.rb index 0dbbb6cf61..29311e8419 100644 --- a/spec/mongoid/association/referenced/has_and_belongs_to_many_models.rb +++ b/spec/mongoid/association/referenced/has_and_belongs_to_many_models.rb @@ -3,8 +3,8 @@ class HabtmmCompany include Mongoid::Document - field :c_id, type: Integer - field :e_ids, type: Array + field :c_id, type: :integer + field :e_ids, type: :array has_and_belongs_to_many :employees, class_name: 'HabtmmEmployee', primary_key: :e_id, foreign_key: :e_ids, inverse_primary_key: :c_id, inverse_foreign_key: :c_ids @@ -13,9 +13,9 @@ class HabtmmCompany class HabtmmEmployee include Mongoid::Document - field :e_id, type: Integer - field :c_ids, type: Array - field :habtmm_company_ids, type: Array + field :e_id, type: :integer + field :c_ids, type: :array + field :habtmm_company_ids, type: :array has_and_belongs_to_many :companies, class_name: 'HabtmmCompany', primary_key: :c_id, foreign_key: :c_ids, inverse_primary_key: :e_id, inverse_foreign_key: :e_ids @@ -26,7 +26,7 @@ class HabtmmContract has_and_belongs_to_many :signatures, class_name: 'HabtmmSignature' - field :item, type: String + field :item, type: :string end class HabtmmSignature @@ -34,8 +34,8 @@ class HabtmmSignature has_and_belongs_to_many :contracts, class_name: 'HabtmmContract' - field :name, type: String - field :year, type: Integer + field :name, type: :string + field :year, type: :integer end class HabtmmTicket @@ -51,7 +51,7 @@ class HabtmmPerson class HabtmmTrainer include Mongoid::Document - field :name, type: String + field :name, type: :string has_and_belongs_to_many :animals, inverse_of: :trainers, class_name: 'HabtmmAnimal', scope: :reptile end @@ -59,7 +59,7 @@ class HabtmmTrainer class HabtmmAnimal include Mongoid::Document - field :taxonomy, type: String + field :taxonomy, type: :string scope :reptile, -> { where(taxonomy: 'reptile') } diff --git a/spec/mongoid/association/referenced/has_many_models.rb b/spec/mongoid/association/referenced/has_many_models.rb index fd096379ba..43019665b8 100644 --- a/spec/mongoid/association/referenced/has_many_models.rb +++ b/spec/mongoid/association/referenced/has_many_models.rb @@ -3,7 +3,7 @@ class HmmCompany include Mongoid::Document - field :p, type: Integer + field :p, type: :integer has_many :emails, primary_key: :p, foreign_key: :f, class_name: 'HmmEmail' # The addresses are added with different dependency mechanisms in tests: @@ -13,7 +13,7 @@ class HmmCompany class HmmEmail include Mongoid::Document - field :f, type: Integer + field :f, type: :integer belongs_to :company, primary_key: :p, foreign_key: :f, class_name: 'HmmCompany' end @@ -28,7 +28,7 @@ class HmmOwner has_many :pets, class_name: 'HmmPet', inverse_of: :current_owner - field :name, type: String + field :name, type: :string end class HmmPet @@ -37,7 +37,7 @@ class HmmPet belongs_to :current_owner, class_name: 'HmmOwner', inverse_of: :pets, optional: true belongs_to :previous_owner, class_name: 'HmmOwner', inverse_of: nil, optional: true - field :name, type: String + field :name, type: :string end class HmmSchool @@ -45,8 +45,8 @@ class HmmSchool has_many :students, class_name: 'HmmStudent' - field :district, type: String - field :team, type: String + field :district, type: :string + field :team, type: :string end class HmmStudent @@ -54,8 +54,8 @@ class HmmStudent belongs_to :school, class_name: 'HmmSchool' - field :name, type: String - field :grade, type: Integer, default: 3 + field :name, type: :string + field :grade, type: :integer, default: 3 end class HmmTicket @@ -79,7 +79,7 @@ class HmmBusSeat class HmmTrainer include Mongoid::Document - field :name, type: String + field :name, type: :string has_many :animals, class_name: 'HmmAnimal', scope: :reptile end @@ -87,7 +87,7 @@ class HmmTrainer class HmmAnimal include Mongoid::Document - field :taxonomy, type: String + field :taxonomy, type: :string scope :reptile, -> { where(taxonomy: 'reptile') } diff --git a/spec/mongoid/association/referenced/has_one_models.rb b/spec/mongoid/association/referenced/has_one_models.rb index c16fe9cd7a..7c4c186cac 100644 --- a/spec/mongoid/association/referenced/has_one_models.rb +++ b/spec/mongoid/association/referenced/has_one_models.rb @@ -8,7 +8,7 @@ class HomCollege # The address is added with different dependency mechanisms in tests: #has_one :address, class_name: 'HomAddress', dependent: :destroy - field :state, type: String + field :state, type: :string end class HomAccreditation @@ -16,8 +16,8 @@ class HomAccreditation belongs_to :college, class_name: 'HomCollege' - field :degree, type: String - field :year, type: Integer, default: 2012 + field :degree, type: :string + field :year, type: :integer, default: 2012 def format 'fmt' @@ -81,7 +81,7 @@ class HomBusDriver class HomTrainer include Mongoid::Document - field :name, type: String + field :name, type: :string has_one :animal, class_name: 'HomAnimal', scope: :reptile end @@ -89,7 +89,7 @@ class HomTrainer class HomAnimal include Mongoid::Document - field :taxonomy, type: String + field :taxonomy, type: :string scope :reptile, -> { where(taxonomy: 'reptile') } diff --git a/spec/mongoid/association_spec.rb b/spec/mongoid/association_spec.rb index 043b451865..a7f39fab49 100644 --- a/spec/mongoid/association_spec.rb +++ b/spec/mongoid/association_spec.rb @@ -7,7 +7,7 @@ before(:all) do Person.field( :_id, - type: BSON::ObjectId, + type: :object_id, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true diff --git a/spec/mongoid/attributes_spec.rb b/spec/mongoid/attributes_spec.rb index 1afcfc7196..ac372fe56a 100644 --- a/spec/mongoid/attributes_spec.rb +++ b/spec/mongoid/attributes_spec.rb @@ -546,7 +546,7 @@ after(:all) do Person.field( :_id, - type: BSON::ObjectId, + type: :object_id, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true @@ -558,7 +558,7 @@ before(:all) do Person.field( :_id, - type: BSON::ObjectId, + type: :object_id, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true @@ -625,7 +625,7 @@ before(:all) do Person.field( :_id, - type: String, + type: :string, pre_processed: true, default: ->{ BSON::ObjectId.new.to_s }, overwrite: true @@ -677,7 +677,7 @@ context "when using integer ids" do before(:all) do - Person.field(:_id, type: Integer, overwrite: true) + Person.field(:_id, type: :integer, overwrite: true) end let(:person) do diff --git a/spec/mongoid/copyable_spec_models.rb b/spec/mongoid/copyable_spec_models.rb index b6b60825ec..7dbab37620 100644 --- a/spec/mongoid/copyable_spec_models.rb +++ b/spec/mongoid/copyable_spec_models.rb @@ -35,13 +35,13 @@ class Blurb class Reg include Mongoid::Document - field :name, type: String + field :name, type: :string end class Dyn include Mongoid::Document include Mongoid::Attributes::Dynamic - field :name, type: String + field :name, type: :string end end diff --git a/spec/mongoid/criteria/findable_spec.rb b/spec/mongoid/criteria/findable_spec.rb index 74e68aadef..f13c5ae9db 100644 --- a/spec/mongoid/criteria/findable_spec.rb +++ b/spec/mongoid/criteria/findable_spec.rb @@ -490,11 +490,11 @@ context "when using string ids" do before(:all) do - Band.field :_id, overwrite: true, type: String + Band.field :_id, overwrite: true, type: :string end after(:all) do - Band.field :_id, overwrite: true, type: BSON::ObjectId, default: ->{ BSON::ObjectId.new } + Band.field :_id, overwrite: true, type: :object_id, default: ->{ BSON::ObjectId.new } end let!(:band) do @@ -686,11 +686,11 @@ context "when using hash ids" do before(:all) do - Band.field :_id, overwrite: true, type: Hash + Band.field :_id, overwrite: true, type: :hash end after(:all) do - Band.field :_id, overwrite: true, type: BSON::ObjectId, default: ->{ BSON::ObjectId.new } + Band.field :_id, overwrite: true, type: :object_id, default: ->{ BSON::ObjectId.new } end let!(:band) do @@ -882,11 +882,11 @@ context "when using integer ids" do before(:all) do - Band.field :_id, overwrite: true, type: Integer + Band.field :_id, overwrite: true, type: :integer end after(:all) do - Band.field :_id, overwrite: true, type: BSON::ObjectId, default: ->{ BSON::ObjectId.new } + Band.field :_id, overwrite: true, type: :object_id, default: ->{ BSON::ObjectId.new } end let!(:band) do diff --git a/spec/mongoid/document_spec.rb b/spec/mongoid/document_spec.rb index 0bf46a6489..f274933b04 100644 --- a/spec/mongoid/document_spec.rb +++ b/spec/mongoid/document_spec.rb @@ -906,7 +906,7 @@ class << self; attr_accessor :name; end Person.validates_format_of(:ssn, without: /\$\$\$/) class Manager < Person - field :level, type: Integer, default: 1 + field :level, type: :integer, default: 1 end end diff --git a/spec/mongoid/fields/foreign_key_spec.rb b/spec/mongoid/fields/foreign_key_spec.rb index af417f6242..edec1b5467 100644 --- a/spec/mongoid/fields/foreign_key_spec.rb +++ b/spec/mongoid/fields/foreign_key_spec.rb @@ -10,7 +10,7 @@ described_class.new( :vals, association: Person.relations["preferences"], - type: Array, + type: :array, default: [], identity: true ) @@ -71,7 +71,7 @@ described_class.new( :vals, association: Person.relations["posts"], - type: Array, + type: :array, default: default, identity: true ) @@ -92,7 +92,7 @@ described_class.new( :vals, association: Person.relations["posts"], - type: Array, + type: :array, default: [], identity: true ) @@ -112,7 +112,7 @@ context "when provided a document" do let(:field) do - described_class.new(:person_id, type: Object, association: association) + described_class.new(:person_id, type: :object, association: association) end let(:game) do @@ -131,7 +131,7 @@ context "when the type is an array" do let(:field) do - described_class.new(:preference_ids, type: Array, default: [], association: association) + described_class.new(:preference_ids, type: :array, default: [], association: association) end context "when providing a single value" do @@ -204,7 +204,7 @@ end let!(:field) do - described_class.new(:account_ids, type: Array, default: [], association: association) + described_class.new(:account_ids, type: :array, default: [], association: association) end let(:id_one) do @@ -267,7 +267,7 @@ end let(:field) do - described_class.new(:person_id, type: Object, association: association) + described_class.new(:person_id, type: :object, association: association) end context "when providing a single value" do @@ -319,7 +319,7 @@ end let(:field) do - described_class.new(:person_id, type: Object, association: association) + described_class.new(:person_id, type: :object, association: association) end context "when the value is an id string" do @@ -391,7 +391,7 @@ end let(:field) do - described_class.new(:person_id, type: Object, association: association) + described_class.new(:person_id, type: :object, association: association) end let(:id_one) do @@ -454,7 +454,7 @@ end let(:field) do - described_class.new(:nameable_id, type: Object, association: association) + described_class.new(:nameable_id, type: :object, association: association) end let(:value) do @@ -476,7 +476,7 @@ context "when the key is resizable" do let(:field) do - described_class.new(:test, type: Array, overwrite: true) + described_class.new(:test, type: :array, overwrite: true) end it "returns true" do @@ -487,7 +487,7 @@ context "when the key is not resizable" do let(:field) do - described_class.new(:test, type: BSON::ObjectId, overwrite: true) + described_class.new(:test, type: :object_id, overwrite: true) end it "returns false" do @@ -509,7 +509,7 @@ let(:field) do described_class.new( :vals, - type: Array, + type: :array, default: [], identity: true, association: association, @@ -559,7 +559,7 @@ before do Person.field( :_id, - type: String, + type: :string, pre_processed: true, default: ->{ BSON::ObjectId.new.to_s }, overwrite: true @@ -569,7 +569,7 @@ after do Person.field( :_id, - type: BSON::ObjectId, + type: :object_id, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true @@ -594,7 +594,7 @@ let(:field) do described_class.new( :vals, - type: Object, + type: :object, default: nil, identity: true, association: association, @@ -626,7 +626,7 @@ before do Person.field( :_id, - type: String, + type: :string, pre_processed: true, default: ->{ BSON::ObjectId.new.to_s }, overwrite: true @@ -636,7 +636,7 @@ after do Person.field( :_id, - type: BSON::ObjectId, + type: :object_id, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true @@ -654,13 +654,13 @@ context "when provided a string" do before do - Person.field(:_id, type: Integer, overwrite: true) + Person.field(:_id, type: :integer, overwrite: true) end after do Person.field( :_id, - type: BSON::ObjectId, + type: :object_id, pre_processed: true, default: ->{ BSON::ObjectId.new }, overwrite: true @@ -682,7 +682,7 @@ context "when the type is an array" do let(:field) do - described_class.new(:vals, type: Array, default: []) + described_class.new(:vals, type: :array, default: []) end it "returns true" do @@ -693,7 +693,7 @@ context "when the type is an object" do let(:field) do - described_class.new(:vals, type: Object, default: []) + described_class.new(:vals, type: :object, default: []) end it "returns false" do diff --git a/spec/mongoid/fields/localized_spec.rb b/spec/mongoid/fields/localized_spec.rb index ecfb4a5a0c..3719168e3d 100644 --- a/spec/mongoid/fields/localized_spec.rb +++ b/spec/mongoid/fields/localized_spec.rb @@ -7,7 +7,7 @@ context "when no default is provided" do let(:field) do - described_class.new(:description, localize: true, type: String) + described_class.new(:description, localize: true, type: :string) end it "defaults to nil" do @@ -24,7 +24,7 @@ :description, localize: true, default: "No translation", - type: String + type: :string ) end @@ -40,7 +40,7 @@ :description, localize: true, default: 1, - type: Integer + type: :integer ) end @@ -55,7 +55,7 @@ context "when the type is a string" do let(:field) do - described_class.new(:description, localize: true, type: String) + described_class.new(:description, localize: true, type: :string) end context "when the field is nil" do @@ -214,7 +214,7 @@ context "when the type is not a string" do let(:field) do - described_class.new(:description, localize: true, type: Integer) + described_class.new(:description, localize: true, type: :integer) end context "when the field is nil" do @@ -325,7 +325,7 @@ context 'when fallbacks are disabled' do let(:field) do - described_class.new(:description, localize: true, type: Integer, fallbacks: false) + described_class.new(:description, localize: true, type: :integer, fallbacks: false) end let(:value) do @@ -363,7 +363,7 @@ context "when the type is a string" do let(:field) do - described_class.new(:description, localize: true, type: String) + described_class.new(:description, localize: true, type: :string) end context "when no locale is defined" do @@ -400,7 +400,7 @@ context "when the type is not a string" do let(:field) do - described_class.new(:description, localize: true, type: Integer) + described_class.new(:description, localize: true, type: :integer) end context "when no locale is defined" do @@ -447,7 +447,7 @@ context "when the value is false" do let(:field) do - described_class.new(:boolean_value, localize: true, type: Mongoid::Boolean) + described_class.new(:boolean_value, localize: true, type: :boolean) end let(:value) do @@ -462,7 +462,7 @@ context "when the value is true" do let(:field) do - described_class.new(:boolean_value, localize: true, type: Mongoid::Boolean) + described_class.new(:boolean_value, localize: true, type: :boolean) end let(:value) do @@ -490,7 +490,7 @@ end let(:field) do - described_class.new(:boolean_value, localize: true, type: Mongoid::Boolean) + described_class.new(:boolean_value, localize: true, type: :boolean) end let(:value) do @@ -509,7 +509,7 @@ end let(:field) do - described_class.new(:boolean_value, localize: true, type: Mongoid::Boolean) + described_class.new(:boolean_value, localize: true, type: :boolean) end let(:value) do diff --git a/spec/mongoid/fields/standard_spec.rb b/spec/mongoid/fields/standard_spec.rb index 0ab98b62ce..d8f87df02f 100644 --- a/spec/mongoid/fields/standard_spec.rb +++ b/spec/mongoid/fields/standard_spec.rb @@ -7,7 +7,7 @@ describe "#lazy?" do let(:field) do - described_class.new(:test, type: String) + described_class.new(:test, type: :string) end it "returns false" do @@ -39,7 +39,7 @@ class FieldTest default: ->{ "testing" }, pre_processed: true, klass: FieldTest, - type: String + type: :string ) end @@ -55,7 +55,7 @@ class FieldTest :test, default: ->{ "testing" }, klass: FieldTest, - type: String + type: :string ) end @@ -72,7 +72,7 @@ class FieldTest :test, default: "testing", klass: FieldTest, - type: String + type: :string ) end @@ -87,7 +87,7 @@ class FieldTest let(:field) do described_class.new( :test, - type: String + type: :string ) end diff --git a/spec/mongoid/fields_spec.rb b/spec/mongoid/fields_spec.rb index 62549de6b5..9eb6bd28cc 100644 --- a/spec/mongoid/fields_spec.rb +++ b/spec/mongoid/fields_spec.rb @@ -321,7 +321,7 @@ end it "converts to Mongoid::Boolean" do - expect(klass.field(:test, type: Mongoid::Boolean).type).to be(Mongoid::Boolean) + expect(klass.field(:test, type: :boolean).type).to be(Mongoid::Boolean) end end @@ -403,7 +403,7 @@ context "when the options are all standard" do before do - Band.field :acceptable, type: Mongoid::Boolean + Band.field :acceptable, type: :boolean end after do @@ -418,7 +418,7 @@ context "when a custom option is provided" do before do - Band.field :acceptable, type: Mongoid::Boolean, custom: true + Band.field :acceptable, type: :boolean, custom: true end it "adds the field to the model" do @@ -745,7 +745,7 @@ context "when provided a default array" do before do - Person.field(:array_testing, type: Array, default: [], overwrite: true) + Person.field(:array_testing, type: :array, default: [], overwrite: true) end after do @@ -763,7 +763,7 @@ context "when provided a default hash" do before do - Person.field(:hash_testing, type: Hash, default: {}, overwrite: true) + Person.field(:hash_testing, type: :hash, default: {}, overwrite: true) end after do @@ -784,7 +784,7 @@ before do Person.field( :generated_testing, - type: Float, + type: :float, default: ->{ Time.now.to_f }, overwrite: true ) @@ -807,7 +807,7 @@ before do Person.field( :rank, - type: Integer, + type: :integer, default: ->{ title? ? 1 : 2 }, overwrite: true ) @@ -989,7 +989,7 @@ def testing=(value) end before do - Person.field :aliased, as: :alias, type: Mongoid::Boolean, overwrite: true + Person.field :aliased, as: :alias, type: :boolean, overwrite: true end it "uses the alias to write the attribute" do @@ -1168,7 +1168,7 @@ class DiscriminatorChild2 < DiscriminatorParent describe ".replace_field" do let!(:original) do - Person.field(:id_test, type: BSON::ObjectId, label: "id") + Person.field(:id_test, type: :object_id, label: "id") end let!(:altered) do diff --git a/spec/mongoid/shardable_models.rb b/spec/mongoid/shardable_models.rb index 4b55f3c15e..7f05e259d4 100644 --- a/spec/mongoid/shardable_models.rb +++ b/spec/mongoid/shardable_models.rb @@ -1,7 +1,7 @@ class SmMovie include Mongoid::Document - field :year, type: Integer + field :year, type: :integer index year: 1 shard_key :year @@ -25,7 +25,7 @@ class SmActor class SmAssistant include Mongoid::Document - field :gender, type: String + field :gender, type: :string index gender: 1 shard_key 'gender' => :hashed diff --git a/spec/mongoid/touchable_spec_models.rb b/spec/mongoid/touchable_spec_models.rb index 7e86d38f12..53f29921c1 100644 --- a/spec/mongoid/touchable_spec_models.rb +++ b/spec/mongoid/touchable_spec_models.rb @@ -16,7 +16,7 @@ class Entrance embedded_in :building - field :last_used_at, type: Time + field :last_used_at, type: :time end class Floor diff --git a/spec/mongoid/traversable_spec.rb b/spec/mongoid/traversable_spec.rb index bc13f7e6fd..33ae025477 100644 --- a/spec/mongoid/traversable_spec.rb +++ b/spec/mongoid/traversable_spec.rb @@ -840,7 +840,7 @@ class PreLocalSymDiscriminatorChild < PreLocalSymDiscriminatorParent class DuplicateDiscriminatorKeyParent include Mongoid::Document - field :dkey, type: String + field :dkey, type: :string end class DuplicateDiscriminatorKeyChild < DuplicateDiscriminatorKeyParent diff --git a/spec/mongoid/validatable/numericality_spec.rb b/spec/mongoid/validatable/numericality_spec.rb index 3fb3c6cf39..cb506b81e9 100644 --- a/spec/mongoid/validatable/numericality_spec.rb +++ b/spec/mongoid/validatable/numericality_spec.rb @@ -9,7 +9,7 @@ before(:all) do class TestModel include Mongoid::Document - field :amount, type: BigDecimal + field :amount, type: :big_decimal validates_numericality_of :amount, allow_blank: false end end diff --git a/spec/support/models/account.rb b/spec/support/models/account.rb index 6f3cbaf4f9..9c638fe7f7 100644 --- a/spec/support/models/account.rb +++ b/spec/support/models/account.rb @@ -3,15 +3,15 @@ class Account include Mongoid::Document - field :_id, type: String, overwrite: true, default: ->{ name.try(:parameterize) } + field :_id, type: :string, overwrite: true, default: ->{ name.try(:parameterize) } - field :number, type: String - field :balance, type: Integer - field :nickname, type: String - field :name, type: String - field :balanced, type: Mongoid::Boolean, default: ->{ balance? ? true : false } + field :number, type: :string + field :balance, type: :integer + field :nickname, type: :string + field :name, type: :string + field :balanced, type: :boolean, default: ->{ balance? ? true : false } - field :overridden, type: String + field :overridden, type: :string embeds_many :memberships belongs_to :creator, class_name: "User", foreign_key: :creator_id @@ -29,7 +29,7 @@ def overridden end # MONGOID-3365 - field :period_started_at, type: Time + field :period_started_at, type: :time has_many :consumption_periods, dependent: :destroy, validate: false def current_consumption diff --git a/spec/support/models/actor.rb b/spec/support/models/actor.rb index 152204e30b..942ec7fe03 100644 --- a/spec/support/models/actor.rb +++ b/spec/support/models/actor.rb @@ -3,7 +3,7 @@ class Actor include Mongoid::Document field :name - field :after_custom_count, type: Integer, default: 0 + field :after_custom_count, type: :integer, default: 0 has_and_belongs_to_many :tags embeds_many :things, validate: false, cascade_callbacks: true accepts_nested_attributes_for :things, allow_destroy: true diff --git a/spec/support/models/address.rb b/spec/support/models/address.rb index 4ba0536aff..3538fc7628 100644 --- a/spec/support/models/address.rb +++ b/spec/support/models/address.rb @@ -3,27 +3,27 @@ class Address include Mongoid::Document - field :_id, type: String, overwrite: true, default: ->{ street.try(:parameterize) } + field :_id, type: :string, overwrite: true, default: ->{ street.try(:parameterize) } attr_accessor :mode field :address_type - field :number, type: Integer - field :no, type: Integer - field :h, as: :house, type: Integer + field :number, type: :integer + field :no, type: :integer + field :h, as: :house, type: :integer field :street field :city field :state field :post_code field :parent_title - field :services, type: Array - field :aliases, as: :a, type: Array - field :test, type: Array - field :latlng, type: Array - field :map, type: Hash - field :move_in, type: DateTime - field :end_date, type: Date - field :s, type: String, as: :suite + field :services, type: :array + field :aliases, as: :a, type: :array + field :test, type: :array + field :latlng, type: :array + field :map, type: :hash + field :move_in, type: :date_time + field :end_date, type: :date + field :s, type: :string, as: :suite field :name, localize: true embeds_many :locations, validate: false diff --git a/spec/support/models/address_component.rb b/spec/support/models/address_component.rb index e7c53a1499..7431e17763 100644 --- a/spec/support/models/address_component.rb +++ b/spec/support/models/address_component.rb @@ -2,6 +2,6 @@ class AddressComponent include Mongoid::Document - field :street, type: String + field :street, type: :string embedded_in :person end diff --git a/spec/support/models/address_number.rb b/spec/support/models/address_number.rb index b0197c5063..34b5787aaf 100644 --- a/spec/support/models/address_number.rb +++ b/spec/support/models/address_number.rb @@ -2,7 +2,7 @@ class AddressNumber include Mongoid::Document - field :country_code, type: Integer, default: 1 + field :country_code, type: :integer, default: 1 field :number embedded_in :slave end diff --git a/spec/support/models/agent.rb b/spec/support/models/agent.rb index 20e107895c..3f8e91ebdb 100644 --- a/spec/support/models/agent.rb +++ b/spec/support/models/agent.rb @@ -3,9 +3,9 @@ class Agent include Mongoid::Document include Mongoid::Timestamps::Updated - field :title, type: String - field :number, type: String - field :dob, type: Time + field :title, type: :string + field :number, type: :string + field :dob, type: :time embeds_many :names, as: :namable embeds_one :address belongs_to :game diff --git a/spec/support/models/alert.rb b/spec/support/models/alert.rb index a9ee1042cb..1dbfb5bcb2 100644 --- a/spec/support/models/alert.rb +++ b/spec/support/models/alert.rb @@ -2,7 +2,7 @@ class Alert include Mongoid::Document - field :message, type: String + field :message, type: :string belongs_to :account has_many :items belongs_to :post diff --git a/spec/support/models/animal.rb b/spec/support/models/animal.rb index 297d8a7046..b776c0f3c7 100644 --- a/spec/support/models/animal.rb +++ b/spec/support/models/animal.rb @@ -3,12 +3,12 @@ class Animal include Mongoid::Document - field :_id, type: String, overwrite: true, default: ->{ name.try(:parameterize) } + field :_id, type: :string, overwrite: true, default: ->{ name.try(:parameterize) } field :name - field :height, type: Integer - field :weight, type: Integer - field :tags, type: Array + field :height, type: :integer + field :weight, type: :integer + field :tags, type: :array embedded_in :person embedded_in :circus, class_name: 'Circus' # class_name is necessary because ActiveRecord think the singular of Circus diff --git a/spec/support/models/answer.rb b/spec/support/models/answer.rb index 451055b9ad..843ff3b243 100644 --- a/spec/support/models/answer.rb +++ b/spec/support/models/answer.rb @@ -4,5 +4,5 @@ class Answer include Mongoid::Document embedded_in :question - field :position, type: Integer + field :position, type: :integer end diff --git a/spec/support/models/appointment.rb b/spec/support/models/appointment.rb index efefbf8c51..8e3ecc89cb 100644 --- a/spec/support/models/appointment.rb +++ b/spec/support/models/appointment.rb @@ -2,8 +2,8 @@ class Appointment include Mongoid::Document - field :active, type: Mongoid::Boolean, default: true - field :timed, type: Mongoid::Boolean, default: true + field :active, type: :boolean, default: true + field :timed, type: :boolean, default: true embedded_in :person default_scope ->{ where(active: true) } end diff --git a/spec/support/models/array_field.rb b/spec/support/models/array_field.rb index dcd1c2ad64..1bee57c69f 100644 --- a/spec/support/models/array_field.rb +++ b/spec/support/models/array_field.rb @@ -3,5 +3,5 @@ class ArrayField include Mongoid::Document - field :af, type: Array + field :af, type: :array end diff --git a/spec/support/models/article.rb b/spec/support/models/article.rb index 728f3a26d4..ccbdf30b17 100644 --- a/spec/support/models/article.rb +++ b/spec/support/models/article.rb @@ -3,11 +3,11 @@ class Article include Mongoid::Document - field :author_id, type: Integer - field :public, type: Mongoid::Boolean - field :title, type: String - field :is_rss, type: Mongoid::Boolean, default: false - field :user_login, type: String + field :author_id, type: :integer + field :public, type: :boolean + field :title, type: :string + field :is_rss, type: :boolean, default: false + field :user_login, type: :string has_and_belongs_to_many :tags, validate: false has_and_belongs_to_many :preferences, inverse_of: nil, validate: false diff --git a/spec/support/models/artist.rb b/spec/support/models/artist.rb index 7e26f72809..7cf74b7a6d 100644 --- a/spec/support/models/artist.rb +++ b/spec/support/models/artist.rb @@ -5,7 +5,7 @@ class Artist attr_accessor :before_add_called, :after_add_called, :before_add_referenced_called, :after_add_referenced_called, :before_remove_embedded_called, :after_remove_embedded_called, :before_remove_referenced_called, :after_remove_referenced_called - field :name, type: String + field :name, type: :string embeds_many :songs, before_add: [ :before_add_song, Proc.new { |artist, song| song.before_add_called = true } ], before_remove: :before_remove_song embeds_many :labels, after_add: :after_add_label, after_remove: :after_remove_label diff --git a/spec/support/models/audio.rb b/spec/support/models/audio.rb index e2c7734e48..a6d73a9ad0 100644 --- a/spec/support/models/audio.rb +++ b/spec/support/models/audio.rb @@ -2,6 +2,6 @@ class Audio include Mongoid::Document - field :likes, type: Integer + field :likes, type: :integer default_scope ->{ self.or({:likes => nil}, {:likes.gt => 100}) } end diff --git a/spec/support/models/author.rb b/spec/support/models/author.rb index e416ab5005..1f74b84248 100644 --- a/spec/support/models/author.rb +++ b/spec/support/models/author.rb @@ -2,7 +2,7 @@ class Author include Mongoid::Document - field :id, type: Integer - field :author, type: Mongoid::Boolean - field :name, type: String + field :id, type: :integer + field :author, type: :boolean + field :name, type: :string end diff --git a/spec/support/models/band.rb b/spec/support/models/band.rb index ab00414885..e5c242531c 100644 --- a/spec/support/models/band.rb +++ b/spec/support/models/band.rb @@ -4,22 +4,22 @@ class Band include Mongoid::Document include Mongoid::Attributes::Dynamic - field :name, type: String - field :active, type: Mongoid::Boolean, default: true - field :origin, type: String - field :genres, type: Array - field :member_count, type: Integer - field :mems, as: :members, type: Array - field :likes, type: Integer - field :views, type: Integer - field :rating, type: Float - field :upserted, type: Mongoid::Boolean, default: false - field :created, type: DateTime - field :sales, type: BigDecimal - field :decimal, type: BSON::Decimal128 - field :y, as: :years, type: Integer - field :founded, type: Date - field :deleted, type: Boolean + field :name, type: :string + field :active, type: :boolean, default: true + field :origin, type: :string + field :genres, type: :array + field :member_count, type: :integer + field :mems, as: :members, type: :array + field :likes, type: :integer + field :views, type: :integer + field :rating, type: :float + field :upserted, type: :boolean, default: false + field :created, type: :date_time + field :sales, type: :big_decimal + field :decimal, type: :decimal128 + field :y, as: :years, type: :integer + field :founded, type: :date + field :deleted, type: :boolean embeds_many :records, cascade_callbacks: true embeds_many :notes, as: :noteable, cascade_callbacks: true, validate: false diff --git a/spec/support/models/bar.rb b/spec/support/models/bar.rb index 70ea6a4a3a..98303a3714 100644 --- a/spec/support/models/bar.rb +++ b/spec/support/models/bar.rb @@ -3,8 +3,8 @@ class Bar include Mongoid::Document include Mongoid::Attributes::Dynamic - field :name, type: String - field :location, type: Array + field :name, type: :string + field :location, type: :array field :lat_lng, type: LatLng has_one :rating, as: :ratable diff --git a/spec/support/models/birthday.rb b/spec/support/models/birthday.rb index de01ee1a36..1588202f45 100644 --- a/spec/support/models/birthday.rb +++ b/spec/support/models/birthday.rb @@ -3,7 +3,7 @@ class Birthday include Mongoid::Document field :title - field :date, type: Date + field :date, type: :date embedded_in :owner, inverse_of: :birthdays def self.each_day(start_date, end_date) diff --git a/spec/support/models/book.rb b/spec/support/models/book.rb index 8aeec493b5..b694b1f001 100644 --- a/spec/support/models/book.rb +++ b/spec/support/models/book.rb @@ -4,8 +4,8 @@ class Book include Mongoid::Document include Mongoid::Attributes::Dynamic include Mongoid::Timestamps - field :title, type: String - field :chapters, type: Integer + field :title, type: :string + field :chapters, type: :integer belongs_to :series belongs_to :person, autobuild: true has_one :rating, as: :ratable, dependent: :nullify diff --git a/spec/support/models/browser.rb b/spec/support/models/browser.rb index b413715952..27a5af0906 100644 --- a/spec/support/models/browser.rb +++ b/spec/support/models/browser.rb @@ -1,7 +1,7 @@ # frozen_string_literal: true class Browser < Canvas - field :version, type: Integer + field :version, type: :integer def render; end end diff --git a/spec/support/models/building_address.rb b/spec/support/models/building_address.rb index a6c90fcfdc..6c811c56be 100644 --- a/spec/support/models/building_address.rb +++ b/spec/support/models/building_address.rb @@ -2,7 +2,7 @@ class BuildingAddress include Mongoid::Document - field :city, type: String + field :city, type: :string embedded_in :building validates_presence_of :city diff --git a/spec/support/models/bus.rb b/spec/support/models/bus.rb index 2cd3fc2c17..85cd2c7a9d 100644 --- a/spec/support/models/bus.rb +++ b/spec/support/models/bus.rb @@ -2,8 +2,8 @@ class Bus include Mongoid::Document - field :saturday, type: Mongoid::Boolean, default: false - field :departure_time, type: Time - field :number, type: Integer + field :saturday, type: :boolean, default: false + field :departure_time, type: :time + field :number, type: :integer embedded_in :circuit end diff --git a/spec/support/models/business.rb b/spec/support/models/business.rb index 82e106f519..e40ddef8d0 100644 --- a/spec/support/models/business.rb +++ b/spec/support/models/business.rb @@ -2,6 +2,6 @@ class Business include Mongoid::Document - field :name, type: String + field :name, type: :string has_and_belongs_to_many :owners, class_name: "User", validate: false end diff --git a/spec/support/models/canvas.rb b/spec/support/models/canvas.rb index e97ede3e2d..4193b8697e 100644 --- a/spec/support/models/canvas.rb +++ b/spec/support/models/canvas.rb @@ -7,7 +7,7 @@ class Canvas embeds_one :writer embeds_one :palette - field :foo, type: String, default: ->{ "original" } + field :foo, type: :string, default: ->{ "original" } has_many :comments, as: :commentable @@ -20,7 +20,7 @@ def render class Test < Canvas - field :foo, type: String, overwrite: true, default: ->{ "overridden" } + field :foo, type: :string, overwrite: true, default: ->{ "overridden" } end end diff --git a/spec/support/models/church.rb b/spec/support/models/church.rb index a24267b02f..f1299965f9 100644 --- a/spec/support/models/church.rb +++ b/spec/support/models/church.rb @@ -3,6 +3,6 @@ class Church include Mongoid::Document has_many :acolytes, validate: false - field :location, type: Hash - field :name, type: String + field :location, type: :hash + field :name, type: :string end diff --git a/spec/support/models/circle.rb b/spec/support/models/circle.rb index a253fffd57..a3f85a1b7a 100644 --- a/spec/support/models/circle.rb +++ b/spec/support/models/circle.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true class Circle < Shape - field :radius, type: Integer, default: 0 + field :radius, type: :integer, default: 0 end diff --git a/spec/support/models/code.rb b/spec/support/models/code.rb index dfde672602..5c49a4633a 100644 --- a/spec/support/models/code.rb +++ b/spec/support/models/code.rb @@ -2,7 +2,7 @@ class Code include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :address embeds_one :deepest end diff --git a/spec/support/models/coding/pull_request.rb b/spec/support/models/coding/pull_request.rb index c5fcd2c425..0961d26d8e 100644 --- a/spec/support/models/coding/pull_request.rb +++ b/spec/support/models/coding/pull_request.rb @@ -4,7 +4,7 @@ module Coding class PullRequest include Mongoid::Document - field :title, type: String + field :title, type: :string has_many :reviews, class_name: 'Publication::Review', as: :reviewable end diff --git a/spec/support/models/comment.rb b/spec/support/models/comment.rb index b0991f0d42..bfdc4a0f53 100644 --- a/spec/support/models/comment.rb +++ b/spec/support/models/comment.rb @@ -3,8 +3,8 @@ class Comment include Mongoid::Document - field :title, type: String - field :text, type: String + field :title, type: :string + field :text, type: :string belongs_to :account belongs_to :movie diff --git a/spec/support/models/consumption_period.rb b/spec/support/models/consumption_period.rb index 58f054ab47..3657fbf17f 100644 --- a/spec/support/models/consumption_period.rb +++ b/spec/support/models/consumption_period.rb @@ -5,5 +5,5 @@ class ConsumptionPeriod belongs_to :account - field :started_at, type: Time + field :started_at, type: :time end diff --git a/spec/support/models/contractor.rb b/spec/support/models/contractor.rb index 851cd46477..8ff5808321 100644 --- a/spec/support/models/contractor.rb +++ b/spec/support/models/contractor.rb @@ -3,5 +3,5 @@ class Contractor include Mongoid::Document embedded_in :building - field :name, type: String + field :name, type: :string end diff --git a/spec/support/models/country_code.rb b/spec/support/models/country_code.rb index 53665f0540..3f750fb6b0 100644 --- a/spec/support/models/country_code.rb +++ b/spec/support/models/country_code.rb @@ -3,9 +3,9 @@ class CountryCode include Mongoid::Document - field :_id, type: Integer, overwrite: true, default: ->{ code } + field :_id, type: :integer, overwrite: true, default: ->{ code } - field :code, type: Integer + field :code, type: :integer field :iso, as: :iso_alpha2_code embedded_in :phone_number, class_name: "Phone" diff --git a/spec/support/models/customer_address.rb b/spec/support/models/customer_address.rb index 024bd352ab..4ee167ad9f 100644 --- a/spec/support/models/customer_address.rb +++ b/spec/support/models/customer_address.rb @@ -3,9 +3,9 @@ class CustomerAddress include Mongoid::Document - field :street, type: String - field :city, type: String - field :state, type: String + field :street, type: :string + field :city, type: :string + field :state, type: :string embedded_in :addressable, polymorphic: true end diff --git a/spec/support/models/deed.rb b/spec/support/models/deed.rb index 45d34944a5..06597ad75f 100644 --- a/spec/support/models/deed.rb +++ b/spec/support/models/deed.rb @@ -2,6 +2,6 @@ class Deed include Mongoid::Document - field :title, type: String + field :title, type: :string embedded_in :owner end diff --git a/spec/support/models/definition.rb b/spec/support/models/definition.rb index 7558196c6b..b48a7dd466 100644 --- a/spec/support/models/definition.rb +++ b/spec/support/models/definition.rb @@ -2,10 +2,10 @@ class Definition include Mongoid::Document - field :description, type: String - field :p, as: :part, type: String - field :regular, type: Mongoid::Boolean - field :syn, as: :synonyms, localize: true, type: String - field :active, type: Mongoid::Boolean, localize: true, default: true + field :description, type: :string + field :p, as: :part, type: :string + field :regular, type: :boolean + field :syn, as: :synonyms, localize: true, type: :string + field :active, type: :boolean, localize: true, default: true embedded_in :word end diff --git a/spec/support/models/dictionary.rb b/spec/support/models/dictionary.rb index 117b9ef202..591cfa3706 100644 --- a/spec/support/models/dictionary.rb +++ b/spec/support/models/dictionary.rb @@ -2,17 +2,17 @@ class Dictionary include Mongoid::Document - field :name, type: String - field :publisher, type: String - field :year, type: Integer + field :name, type: :string + field :publisher, type: :string + field :year, type: :integer # This field must be a Time - field :published, type: Time + field :published, type: :time # This field must be a Date - field :submitted_on, type: Date + field :submitted_on, type: :date - field :description, type: String, localize: true - field :l, type: String, as: :language + field :description, type: :string, localize: true + field :l, type: :string, as: :language has_many :words, validate: false end diff --git a/spec/support/models/division.rb b/spec/support/models/division.rb index 99ff805eb1..7bc1d76c50 100644 --- a/spec/support/models/division.rb +++ b/spec/support/models/division.rb @@ -2,7 +2,7 @@ class Division include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :league before_destroy :update_parent diff --git a/spec/support/models/dog.rb b/spec/support/models/dog.rb index 059ef57e89..fea5f96aa2 100644 --- a/spec/support/models/dog.rb +++ b/spec/support/models/dog.rb @@ -2,7 +2,7 @@ class Dog include Mongoid::Document - field :name, type: String + field :name, type: :string has_and_belongs_to_many :breeds has_and_belongs_to_many :fire_hydrants, primary_key: :location default_scope ->{ asc(:name) } diff --git a/spec/support/models/drug.rb b/spec/support/models/drug.rb index ad99c90260..8eae3013e0 100644 --- a/spec/support/models/drug.rb +++ b/spec/support/models/drug.rb @@ -2,7 +2,7 @@ class Drug include Mongoid::Document - field :name, type: String - field :generic, type: Mongoid::Boolean + field :name, type: :string + field :generic, type: :boolean belongs_to :person, counter_cache: true end diff --git a/spec/support/models/entry.rb b/spec/support/models/entry.rb index da58bc236a..2773514813 100644 --- a/spec/support/models/entry.rb +++ b/spec/support/models/entry.rb @@ -2,7 +2,7 @@ class Entry include Mongoid::Document - field :title, type: String - field :body, type: String + field :title, type: :string + field :body, type: :string recursively_embeds_many end diff --git a/spec/support/models/event.rb b/spec/support/models/event.rb index 37dda1651e..6f793e2cd9 100644 --- a/spec/support/models/event.rb +++ b/spec/support/models/event.rb @@ -4,7 +4,7 @@ class Event include Mongoid::Document field :title - field :date, type: Date + field :date, type: :date has_and_belongs_to_many \ :administrators, class_name: 'Person', diff --git a/spec/support/models/exhibitor.rb b/spec/support/models/exhibitor.rb index 9b26ac4617..0be14be10e 100644 --- a/spec/support/models/exhibitor.rb +++ b/spec/support/models/exhibitor.rb @@ -2,7 +2,7 @@ class Exhibitor include Mongoid::Document - field :status, type: String + field :status, type: :string belongs_to :exhibition has_and_belongs_to_many :artworks end diff --git a/spec/support/models/eye.rb b/spec/support/models/eye.rb index 56fd31dd2f..1daae4aa07 100644 --- a/spec/support/models/eye.rb +++ b/spec/support/models/eye.rb @@ -3,7 +3,7 @@ class Eye include Mongoid::Document - field :pupil_dilation, type: Integer + field :pupil_dilation, type: :integer belongs_to :eyeable, polymorphic: true diff --git a/spec/support/models/fire_hydrant.rb b/spec/support/models/fire_hydrant.rb index a8d1834b7a..179bd1848c 100644 --- a/spec/support/models/fire_hydrant.rb +++ b/spec/support/models/fire_hydrant.rb @@ -2,7 +2,7 @@ class FireHydrant include Mongoid::Document - field :location, type: String + field :location, type: :string has_and_belongs_to_many :dogs, primary_key: :name has_and_belongs_to_many :cats, primary_key: :name end diff --git a/spec/support/models/folder.rb b/spec/support/models/folder.rb index bcec86c4a2..944b4c22e4 100644 --- a/spec/support/models/folder.rb +++ b/spec/support/models/folder.rb @@ -3,7 +3,7 @@ class Folder include Mongoid::Document - field :name, type: String + field :name, type: :string has_many :folder_items end diff --git a/spec/support/models/folder_item.rb b/spec/support/models/folder_item.rb index 6c50e21d37..25ca112c14 100644 --- a/spec/support/models/folder_item.rb +++ b/spec/support/models/folder_item.rb @@ -5,7 +5,7 @@ class FolderItem include Mongoid::Document belongs_to :folder - field :name, type: String + field :name, type: :string validates :name, uniqueness: {scope: :folder_id} end diff --git a/spec/support/models/game.rb b/spec/support/models/game.rb index 2fce9e5dc9..f759e0f5f2 100644 --- a/spec/support/models/game.rb +++ b/spec/support/models/game.rb @@ -3,8 +3,8 @@ class Game include Mongoid::Document - field :high_score, type: Integer, default: 500 - field :score, type: Integer, default: 0 + field :high_score, type: :integer, default: 500 + field :score, type: :integer, default: 0 field :name belongs_to :person, index: true, validate: true diff --git a/spec/support/models/ghost.rb b/spec/support/models/ghost.rb index 41c809aa1d..1b56e0f26d 100644 --- a/spec/support/models/ghost.rb +++ b/spec/support/models/ghost.rb @@ -3,7 +3,7 @@ class Ghost include Mongoid::Document - field :name, type: String + field :name, type: :string belongs_to :movie, autosave: true end diff --git a/spec/support/models/house.rb b/spec/support/models/house.rb index 5576f2ed1b..28caddfee6 100644 --- a/spec/support/models/house.rb +++ b/spec/support/models/house.rb @@ -2,7 +2,7 @@ class House include Mongoid::Document - field :name, type: String - field :model, type: String + field :name, type: :string + field :model, type: :string default_scope ->{ asc(:name) } end diff --git a/spec/support/models/idnodef.rb b/spec/support/models/idnodef.rb index f811920518..2f57d96394 100644 --- a/spec/support/models/idnodef.rb +++ b/spec/support/models/idnodef.rb @@ -3,5 +3,5 @@ class Idnodef include Mongoid::Document - field :_id, type: String, overwrite: true + field :_id, type: :string, overwrite: true end diff --git a/spec/support/models/implant.rb b/spec/support/models/implant.rb index 71b1cbd73c..e3c5eb65e1 100644 --- a/spec/support/models/implant.rb +++ b/spec/support/models/implant.rb @@ -4,7 +4,7 @@ class Implant include Mongoid::Document field :name - field :impressions, type: Integer, default: 0 + field :impressions, type: :integer, default: 0 embedded_in :player, inverse_of: :implants diff --git a/spec/support/models/item.rb b/spec/support/models/item.rb index 85cb8c3bb5..2fe8e0a476 100644 --- a/spec/support/models/item.rb +++ b/spec/support/models/item.rb @@ -2,9 +2,9 @@ class Item include Mongoid::Document - field :title, type: String - field :is_rss, type: Mongoid::Boolean, default: false - field :user_login, type: String + field :title, type: :string + field :is_rss, type: :boolean, default: false + field :user_login, type: :string end require "support/models/sub_item" diff --git a/spec/support/models/jar.rb b/spec/support/models/jar.rb index f0afc662ee..39e9337bbb 100644 --- a/spec/support/models/jar.rb +++ b/spec/support/models/jar.rb @@ -4,6 +4,6 @@ class Jar include Mongoid::Document include Mongoid::Timestamps::Updated - field :_id, type: Integer, overwrite: true + field :_id, type: :integer, overwrite: true has_many :cookies, class_name: "Cookie" end diff --git a/spec/support/models/kaleidoscope.rb b/spec/support/models/kaleidoscope.rb index 4ef75a0941..e5afbb6d86 100644 --- a/spec/support/models/kaleidoscope.rb +++ b/spec/support/models/kaleidoscope.rb @@ -2,7 +2,7 @@ class Kaleidoscope include Mongoid::Document - field :active, type: Mongoid::Boolean, default: true + field :active, type: :boolean, default: true scope :activated, -> { where(active: true) } end diff --git a/spec/support/models/label.rb b/spec/support/models/label.rb index 6dbc3eab78..2267f481f1 100644 --- a/spec/support/models/label.rb +++ b/spec/support/models/label.rb @@ -4,13 +4,13 @@ class Label include Mongoid::Document include Mongoid::Timestamps::Updated::Short - field :name, type: String - field :after_create_called, type: Mongoid::Boolean, default: false - field :after_save_called, type: Mongoid::Boolean, default: false - field :after_update_called, type: Mongoid::Boolean, default: false - field :after_validation_called, type: Mongoid::Boolean, default: false + field :name, type: :string + field :after_create_called, type: :boolean, default: false + field :after_save_called, type: :boolean, default: false + field :after_update_called, type: :boolean, default: false + field :after_validation_called, type: :boolean, default: false - field :before_save_count, type: Integer, default: 0 + field :before_save_count, type: :integer, default: 0 embedded_in :artist embedded_in :band diff --git a/spec/support/models/language.rb b/spec/support/models/language.rb index e4a84f73f1..ae0ae79859 100644 --- a/spec/support/models/language.rb +++ b/spec/support/models/language.rb @@ -2,6 +2,6 @@ class Language include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :translatable, polymorphic: true end diff --git a/spec/support/models/league.rb b/spec/support/models/league.rb index a93a4d236f..baa24ba53b 100644 --- a/spec/support/models/league.rb +++ b/spec/support/models/league.rb @@ -2,7 +2,7 @@ class League include Mongoid::Document - field :name, type: String + field :name, type: :string embeds_many :divisions accepts_nested_attributes_for :divisions, allow_destroy: true before_destroy :destroy_children diff --git a/spec/support/models/location.rb b/spec/support/models/location.rb index 87c01ef6c4..1a7471c164 100644 --- a/spec/support/models/location.rb +++ b/spec/support/models/location.rb @@ -3,8 +3,8 @@ class Location include Mongoid::Document field :name - field :info, type: Hash - field :occupants, type: Array - field :number, type: Integer + field :info, type: :hash + field :occupants, type: :array + field :number, type: :integer embedded_in :address end diff --git a/spec/support/models/login.rb b/spec/support/models/login.rb index 4fda3d0d62..06754219a3 100644 --- a/spec/support/models/login.rb +++ b/spec/support/models/login.rb @@ -3,8 +3,8 @@ class Login include Mongoid::Document - field :_id, type: String, overwrite: true, default: ->{ username } + field :_id, type: :string, overwrite: true, default: ->{ username } - field :username, type: String - field :application_id, type: Integer + field :username, type: :string + field :application_id, type: :integer end diff --git a/spec/support/models/manufacturer.rb b/spec/support/models/manufacturer.rb index 8cc685239b..520e73f2db 100644 --- a/spec/support/models/manufacturer.rb +++ b/spec/support/models/manufacturer.rb @@ -3,7 +3,7 @@ class Manufacturer include Mongoid::Document - field :products, type: Array, default: [] + field :products, type: :array, default: [] validates_presence_of :products end diff --git a/spec/support/models/message.rb b/spec/support/models/message.rb index 7b3c089037..2cfaa8c40f 100644 --- a/spec/support/models/message.rb +++ b/spec/support/models/message.rb @@ -3,8 +3,8 @@ class Message include Mongoid::Document - field :body, type: String - field :priority, type: Integer + field :body, type: :string + field :priority, type: :integer embedded_in :person has_and_belongs_to_many :receivers, class_name: "Person", inverse_of: nil diff --git a/spec/support/models/mop.rb b/spec/support/models/mop.rb index 12782a083f..562c4b906c 100644 --- a/spec/support/models/mop.rb +++ b/spec/support/models/mop.rb @@ -10,15 +10,15 @@ class Mop # We need some fields of specific types because the query conditions are # transformed differently based on the type of field being queried. - field :int_field, type: Integer - field :array_field, type: Array - field :date_field, type: Date - field :time_field, type: Time - field :datetime_field, type: DateTime - field :big_decimal_field, type: BigDecimal - field :decimal128_field, type: BSON::Decimal128 - field :symbol_field, type: Symbol - field :bson_symbol_field, type: BSON::Symbol::Raw - field :regexp_field, type: Regexp - field :bson_regexp_field, type: BSON::Regexp::Raw + field :int_field, type: :integer + field :array_field, type: :array + field :date_field, type: :date + field :time_field, type: :time + field :datetime_field, type: :date_time + field :big_decimal_field, type: :big_decimal + field :decimal128_field, type: :decimal128 + field :symbol_field, type: :symbol + field :bson_symbol_field, type: :bson_symbol + field :regexp_field, type: :regexp + field :bson_regexp_field, type: :bson_regexp end diff --git a/spec/support/models/movie.rb b/spec/support/models/movie.rb index 449ff00441..764f8aa486 100644 --- a/spec/support/models/movie.rb +++ b/spec/support/models/movie.rb @@ -3,7 +3,7 @@ class Movie include Mongoid::Document include Mongoid::Attributes::Dynamic - field :title, type: String + field :title, type: :string field :poster, type: Image field :poster_thumb, type: Thumbnail has_many :ratings, as: :ratable, dependent: :nullify diff --git a/spec/support/models/name.rb b/spec/support/models/name.rb index e6740e12ec..7037204d28 100644 --- a/spec/support/models/name.rb +++ b/spec/support/models/name.rb @@ -4,14 +4,14 @@ class Name include Mongoid::Document include Mongoid::Attributes::Dynamic - field :_id, type: String, overwrite: true, default: ->{ + field :_id, type: :string, overwrite: true, default: ->{ "#{first_name}-#{last_name}" } - field :first_name, type: String - field :last_name, type: String - field :parent_title, type: String - field :middle, type: String + field :first_name, type: :string + field :last_name, type: :string + field :parent_title, type: :string + field :middle, type: :string embeds_many :translations, validate: false embeds_one :language, as: :translatable, validate: false diff --git a/spec/support/models/name_only.rb b/spec/support/models/name_only.rb index 5604107dd4..d7a958cb45 100644 --- a/spec/support/models/name_only.rb +++ b/spec/support/models/name_only.rb @@ -4,5 +4,5 @@ class NameOnly include Mongoid::Document - field :name, type: String + field :name, type: :string end diff --git a/spec/support/models/note.rb b/spec/support/models/note.rb index 196e70acfd..e93a5c4e0d 100644 --- a/spec/support/models/note.rb +++ b/spec/support/models/note.rb @@ -2,8 +2,8 @@ class Note include Mongoid::Document - field :text, type: String - field :saved, type: Mongoid::Boolean, default: false + field :text, type: :string + field :saved, type: :boolean, default: false embedded_in :noteable, polymorphic: true after_save :update_saved diff --git a/spec/support/models/order.rb b/spec/support/models/order.rb index c46aadffca..b96c195cab 100644 --- a/spec/support/models/order.rb +++ b/spec/support/models/order.rb @@ -2,7 +2,7 @@ class Order include Mongoid::Document - field :status, type: Mongoid::StringifiedSymbol + field :status, type: :stringified_symbol # This is a dummy field that verifies the Mongoid::Fields::StringifiedSymbol # alias. diff --git a/spec/support/models/ordered_post.rb b/spec/support/models/ordered_post.rb index c502c7d901..9439b469c8 100644 --- a/spec/support/models/ordered_post.rb +++ b/spec/support/models/ordered_post.rb @@ -2,8 +2,8 @@ class OrderedPost include Mongoid::Document - field :title, type: String - field :rating, type: Integer + field :title, type: :string + field :rating, type: :integer belongs_to :person after_destroy do diff --git a/spec/support/models/ordered_preference.rb b/spec/support/models/ordered_preference.rb index f32d4fac2d..2f25a2cfe4 100644 --- a/spec/support/models/ordered_preference.rb +++ b/spec/support/models/ordered_preference.rb @@ -2,7 +2,7 @@ class OrderedPreference include Mongoid::Document - field :name, type: String - field :value, type: String + field :name, type: :string + field :value, type: :string has_and_belongs_to_many :people, validate: false end diff --git a/spec/support/models/oscar.rb b/spec/support/models/oscar.rb index 1c3d3c1b0b..89f9c24852 100644 --- a/spec/support/models/oscar.rb +++ b/spec/support/models/oscar.rb @@ -2,8 +2,8 @@ class Oscar include Mongoid::Document - field :title, type: String - field :destroy_after_save, type: Mongoid::Boolean, default: false + field :title, type: :string + field :destroy_after_save, type: :boolean, default: false before_save :complain def complain diff --git a/spec/support/models/parent_doc.rb b/spec/support/models/parent_doc.rb index c6672caea6..f3577be7ec 100644 --- a/spec/support/models/parent_doc.rb +++ b/spec/support/models/parent_doc.rb @@ -3,6 +3,6 @@ class ParentDoc include Mongoid::Document field :statistic - field :children_order, type: Array, default: [] # hold all the children's id + field :children_order, type: :array, default: [] # hold all the children's id embeds_many :children, class_name: 'ChildDoc', inverse_of: :parent_doc end diff --git a/spec/support/models/passport.rb b/spec/support/models/passport.rb index 91159b5f3a..9ffa0c3560 100644 --- a/spec/support/models/passport.rb +++ b/spec/support/models/passport.rb @@ -3,9 +3,9 @@ class Passport include Mongoid::Document - field :number, type: String - field :country, type: String - field :exp, as: :expiration_date, type: Date + field :number, type: :string + field :country, type: :string + field :exp, as: :expiration_date, type: :date embedded_in :person, autobuild: true end diff --git a/spec/support/models/patient.rb b/spec/support/models/patient.rb index abfecf75fb..7a4d5481e9 100644 --- a/spec/support/models/patient.rb +++ b/spec/support/models/patient.rb @@ -2,7 +2,7 @@ class Patient include Mongoid::Document - field :title, type: String + field :title, type: :string store_in collection: "inpatient" embeds_many :addresses, as: :addressable embeds_one :email diff --git a/spec/support/models/person.rb b/spec/support/models/person.rb index 93facb114d..357a2102b6 100644 --- a/spec/support/models/person.rb +++ b/spec/support/models/person.rb @@ -10,35 +10,35 @@ class Person field :username, default: -> { "arthurnn#{rand(0..10)}" } field :title - field :terms, type: Mongoid::Boolean - field :pets, type: Mongoid::Boolean, default: false - field :age, type: Integer, default: "100" - field :dob, type: Date + field :terms, type: :boolean + field :pets, type: :boolean, default: false + field :age, type: :integer, default: "100" + field :dob, type: :date field :employer_id - field :lunch_time, type: Time - field :aliases, type: Array - field :map, type: Hash - field :map_with_default, type: Hash, default: {} - field :score, type: Integer - field :blood_alcohol_content, type: Float, default: ->{ 0.0 } - field :last_drink_taken_at, type: Date, default: ->{ 1.day.ago.in_time_zone("Alaska") } + field :lunch_time, type: :time + field :aliases, type: :array + field :map, type: :hash + field :map_with_default, type: :hash, default: {} + field :score, type: :integer + field :blood_alcohol_content, type: :float, default: ->{ 0.0 } + field :last_drink_taken_at, type: :date, default: ->{ 1.day.ago.in_time_zone("Alaska") } field :ssn - field :owner_id, type: Integer + field :owner_id, type: :integer field :security_code - field :reading, type: Object - field :bson_id, type: BSON::ObjectId - field :pattern, type: Regexp - field :override_me, type: Integer - field :at, as: :aliased_timestamp, type: Time - field :t, as: :test, type: String - field :i, as: :inte, type: Integer - field :a, as: :array, type: Array + field :reading, type: :object + field :bson_id, type: :object_id + field :pattern, type: :regexp + field :override_me, type: :integer + field :at, as: :aliased_timestamp, type: :time + field :t, as: :test, type: :string + field :i, as: :inte, type: :integer + field :a, as: :array, type: :array field :desc, localize: true - field :test_array, type: Array - field :overridden_setter, type: String - field :arrays, type: Array - field :range, type: Range - field :species, type: Symbol + field :test_array, type: :array + field :overridden_setter, type: :string + field :arrays, type: :array + field :range, type: :range + field :species, type: :symbol index age: 1 index addresses: 1 diff --git a/spec/support/models/pet.rb b/spec/support/models/pet.rb index 9c41acd66f..0e1376db02 100644 --- a/spec/support/models/pet.rb +++ b/spec/support/models/pet.rb @@ -3,7 +3,7 @@ class Pet include Mongoid::Document field :name - field :weight, type: Float, default: 0.0 + field :weight, type: :float, default: 0.0 embeds_many :vet_visits embedded_in :pet_owner diff --git a/spec/support/models/phone.rb b/spec/support/models/phone.rb index 3d8ca55dcd..fedecf2091 100644 --- a/spec/support/models/phone.rb +++ b/spec/support/models/phone.rb @@ -3,10 +3,10 @@ class Phone include Mongoid::Document - field :_id, type: String, overwrite: true, default: ->{ number } + field :_id, type: :string, overwrite: true, default: ->{ number } field :number field :ext, as: :extension - field :landline, type: Boolean + field :landline, type: :boolean embeds_one :country_code embedded_in :person diff --git a/spec/support/models/pizza.rb b/spec/support/models/pizza.rb index 5444c2a883..b79fc65915 100644 --- a/spec/support/models/pizza.rb +++ b/spec/support/models/pizza.rb @@ -2,7 +2,7 @@ class Pizza include Mongoid::Document - field :name, type: String + field :name, type: :string has_one :topping, autosave: true validates_presence_of :topping accepts_nested_attributes_for :topping diff --git a/spec/support/models/player.rb b/spec/support/models/player.rb index 4a1c4a982c..0417e63ad7 100644 --- a/spec/support/models/player.rb +++ b/spec/support/models/player.rb @@ -2,10 +2,10 @@ class Player include Mongoid::Document - field :active, type: Mongoid::Boolean - field :frags, type: Integer - field :deaths, type: Integer - field :impressions, type: Integer, default: 0 + field :active, type: :boolean + field :frags, type: :integer + field :deaths, type: :integer + field :impressions, type: :integer, default: 0 field :status scope :active, ->{ where(active: true) } do diff --git a/spec/support/models/post.rb b/spec/support/models/post.rb index cc295bd9b1..19bff5a006 100644 --- a/spec/support/models/post.rb +++ b/spec/support/models/post.rb @@ -4,10 +4,10 @@ class Post include Mongoid::Document include Mongoid::Attributes::Dynamic - field :title, type: String - field :content, type: String - field :rating, type: Integer - field :person_title, type: String, default: ->{ person.title if ivar(:person) } + field :title, type: :string + field :content, type: :string + field :rating, type: :integer + field :person_title, type: :string, default: ->{ person.title if ivar(:person) } attr_accessor :before_add_called, :after_add_called, :before_remove_called, :after_remove_called diff --git a/spec/support/models/post_genre.rb b/spec/support/models/post_genre.rb index bf659ecb7e..e514157454 100644 --- a/spec/support/models/post_genre.rb +++ b/spec/support/models/post_genre.rb @@ -2,7 +2,7 @@ class PostGenre include Mongoid::Document - field :posts_count, type: Integer, default: 0 + field :posts_count, type: :integer, default: 0 has_many :posts, inverse_of: :genre end diff --git a/spec/support/models/preference.rb b/spec/support/models/preference.rb index 1cbe4a1a62..96cc0c762f 100644 --- a/spec/support/models/preference.rb +++ b/spec/support/models/preference.rb @@ -2,9 +2,9 @@ class Preference include Mongoid::Document - field :name, type: String - field :value, type: String - field :ranking, type: Integer + field :name, type: :string + field :value, type: :string + field :ranking, type: :integer has_and_belongs_to_many :people, validate: false validates_length_of :name, minimum: 2, allow_nil: true scope :posting, ->{ where(:value.in => [ "Posting" ]) } diff --git a/spec/support/models/princess.rb b/spec/support/models/princess.rb index 8e106d893f..de5365aaff 100644 --- a/spec/support/models/princess.rb +++ b/spec/support/models/princess.rb @@ -3,7 +3,7 @@ class Princess include Mongoid::Document field :primary_color - field :name, type: String + field :name, type: :string def color primary_color.to_s end diff --git a/spec/support/models/product.rb b/spec/support/models/product.rb index 94392bf604..77b9ee4ce8 100644 --- a/spec/support/models/product.rb +++ b/spec/support/models/product.rb @@ -4,9 +4,9 @@ class Product include Mongoid::Document field :description, localize: true field :name, localize: true, default: "no translation" - field :price, type: Integer + field :price, type: :integer field :brand_name - field :stores, type: Array + field :stores, type: :array field :website, localize: true field :sku, as: :stock_keeping_unit field :tl, as: :tagline, localize: true diff --git a/spec/support/models/profile.rb b/spec/support/models/profile.rb index 72fb1145ff..e8f85de081 100644 --- a/spec/support/models/profile.rb +++ b/spec/support/models/profile.rb @@ -2,7 +2,7 @@ class Profile include Mongoid::Document - field :name, type: String + field :name, type: :string embeds_one :profile_image @@ -11,7 +11,7 @@ class Profile class ProfileImage include Mongoid::Document - field :url, type: String + field :url, type: :string embedded_in :profile end diff --git a/spec/support/models/pronunciation.rb b/spec/support/models/pronunciation.rb index 9f1b66b5d6..6b985a0e20 100644 --- a/spec/support/models/pronunciation.rb +++ b/spec/support/models/pronunciation.rb @@ -2,6 +2,6 @@ class Pronunciation include Mongoid::Document - field :sound, type: String + field :sound, type: :string embedded_in :word end diff --git a/spec/support/models/pub.rb b/spec/support/models/pub.rb index e1d416eaa9..2c9a7d9f90 100644 --- a/spec/support/models/pub.rb +++ b/spec/support/models/pub.rb @@ -3,6 +3,6 @@ class Pub include Mongoid::Document include Mongoid::Attributes::Dynamic - field :location, type: Array + field :location, type: :array index location: "2dsphere" end diff --git a/spec/support/models/publication/encyclopedia.rb b/spec/support/models/publication/encyclopedia.rb index 72cd80db4a..baf20f70ca 100644 --- a/spec/support/models/publication/encyclopedia.rb +++ b/spec/support/models/publication/encyclopedia.rb @@ -4,7 +4,7 @@ module Publication class Encyclopedia include Mongoid::Document - field :title, type: String + field :title, type: :string has_many :reviews, class_name: 'Publication::Review', as: :reviewable end diff --git a/spec/support/models/quiz.rb b/spec/support/models/quiz.rb index 3524394bc2..43621cad9a 100644 --- a/spec/support/models/quiz.rb +++ b/spec/support/models/quiz.rb @@ -3,7 +3,7 @@ class Quiz include Mongoid::Document include Mongoid::Timestamps::Created - field :name, type: String - field :topic, type: String + field :name, type: :string + field :topic, type: :string embeds_many :pages end diff --git a/spec/support/models/rating.rb b/spec/support/models/rating.rb index 42fec39dde..e9d323d45b 100644 --- a/spec/support/models/rating.rb +++ b/spec/support/models/rating.rb @@ -2,7 +2,7 @@ class Rating include Mongoid::Document - field :value, type: Integer + field :value, type: :integer belongs_to :ratable, polymorphic: true has_many :comments validates_numericality_of :value, less_than: 100, allow_nil: true diff --git a/spec/support/models/record.rb b/spec/support/models/record.rb index 25682e0449..4f3f918be3 100644 --- a/spec/support/models/record.rb +++ b/spec/support/models/record.rb @@ -2,14 +2,14 @@ class Record include Mongoid::Document - field :name, type: String - field :producers, type: Array - - field :before_create_called, type: Mongoid::Boolean, default: false - field :before_save_called, type: Mongoid::Boolean, default: false - field :before_update_called, type: Mongoid::Boolean, default: false - field :before_validation_called, type: Mongoid::Boolean, default: false - field :before_destroy_called, type: Mongoid::Boolean, default: false + field :name, type: :string + field :producers, type: :array + + field :before_create_called, type: :boolean, default: false + field :before_save_called, type: :boolean, default: false + field :before_update_called, type: :boolean, default: false + field :before_validation_called, type: :boolean, default: false + field :before_destroy_called, type: :boolean, default: false embedded_in :band embeds_many :tracks, cascade_callbacks: true diff --git a/spec/support/models/registry.rb b/spec/support/models/registry.rb index 103e7a28c4..7c4f9ef1f8 100644 --- a/spec/support/models/registry.rb +++ b/spec/support/models/registry.rb @@ -2,5 +2,5 @@ class Registry include Mongoid::Document - field :data, type: BSON::Binary + field :data, type: :binary end diff --git a/spec/support/models/role.rb b/spec/support/models/role.rb index c3c2582993..4aff439deb 100644 --- a/spec/support/models/role.rb +++ b/spec/support/models/role.rb @@ -2,7 +2,7 @@ class Role include Mongoid::Document - field :name, type: String + field :name, type: :string belongs_to :user belongs_to :post recursively_embeds_many diff --git a/spec/support/models/sandwich.rb b/spec/support/models/sandwich.rb index c53ec2fa16..d4c39ec935 100644 --- a/spec/support/models/sandwich.rb +++ b/spec/support/models/sandwich.rb @@ -4,7 +4,7 @@ class Sandwich include Mongoid::Document has_and_belongs_to_many :meats - field :name, type: String + field :name, type: :string belongs_to :posteable, polymorphic: true accepts_nested_attributes_for :posteable, autosave: true diff --git a/spec/support/models/scribe.rb b/spec/support/models/scribe.rb index b4aa57da42..c65ad7b914 100644 --- a/spec/support/models/scribe.rb +++ b/spec/support/models/scribe.rb @@ -2,6 +2,6 @@ class Scribe include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :owner end diff --git a/spec/support/models/seat.rb b/spec/support/models/seat.rb index c1a016995d..53fab8ec22 100644 --- a/spec/support/models/seat.rb +++ b/spec/support/models/seat.rb @@ -5,7 +5,7 @@ class Seat embedded_in :vehicle - field :rating, type: Integer + field :rating, type: :integer embeds_many :armrests diff --git a/spec/support/models/seo.rb b/spec/support/models/seo.rb index 158ba9d6d7..a521996f95 100644 --- a/spec/support/models/seo.rb +++ b/spec/support/models/seo.rb @@ -3,7 +3,7 @@ class Seo include Mongoid::Document include Mongoid::Timestamps - field :title, type: String + field :title, type: :string embedded_in :seo_tags, polymorphic: true end diff --git a/spec/support/models/server.rb b/spec/support/models/server.rb index 8ddef36b35..bef731fe87 100644 --- a/spec/support/models/server.rb +++ b/spec/support/models/server.rb @@ -2,8 +2,8 @@ class Server include Mongoid::Document - field :name, type: String - field :after, type: Mongoid::Boolean, default: false + field :name, type: :string + field :after, type: :boolean, default: false belongs_to :node embeds_many :filesystems, validate: false accepts_nested_attributes_for :filesystems diff --git a/spec/support/models/service.rb b/spec/support/models/service.rb index bc5e442d4a..337335c596 100644 --- a/spec/support/models/service.rb +++ b/spec/support/models/service.rb @@ -3,9 +3,9 @@ class Service include Mongoid::Document field :sid - field :before_destroy_called, type: Mongoid::Boolean, default: false - field :after_destroy_called, type: Mongoid::Boolean, default: false - field :after_initialize_called, type: Mongoid::Boolean, default: false + field :before_destroy_called, type: :boolean, default: false + field :after_destroy_called, type: :boolean, default: false + field :after_initialize_called, type: :boolean, default: false embedded_in :person belongs_to :target, class_name: "User" validates_numericality_of :sid diff --git a/spec/support/models/shape.rb b/spec/support/models/shape.rb index 3180be3c70..653625d2a6 100644 --- a/spec/support/models/shape.rb +++ b/spec/support/models/shape.rb @@ -2,8 +2,8 @@ class Shape include Mongoid::Document - field :x, type: Integer, default: 0 - field :y, type: Integer, default: 0 + field :x, type: :integer, default: 0 + field :y, type: :integer, default: 0 embedded_in :canvas diff --git a/spec/support/models/shelf.rb b/spec/support/models/shelf.rb index 2ab8cb1c72..5f3d79e729 100644 --- a/spec/support/models/shelf.rb +++ b/spec/support/models/shelf.rb @@ -2,6 +2,6 @@ class Shelf include Mongoid::Document - field :level, type: Integer + field :level, type: :integer recursively_embeds_one end diff --git a/spec/support/models/shirt.rb b/spec/support/models/shirt.rb index 4314c95ddc..3507a6cb38 100644 --- a/spec/support/models/shirt.rb +++ b/spec/support/models/shirt.rb @@ -3,9 +3,9 @@ class Shirt include Mongoid::Document - field :color, type: String + field :color, type: :string unalias_attribute :id - field :id, type: String + field :id, type: :string end diff --git a/spec/support/models/shop.rb b/spec/support/models/shop.rb index 48e7b07ce9..7d20b14a0c 100644 --- a/spec/support/models/shop.rb +++ b/spec/support/models/shop.rb @@ -2,7 +2,7 @@ class Shop include Mongoid::Document - field :title, type: String + field :title, type: :string has_and_belongs_to_many :followers, inverse_of: :followed_shops, class_name: "User" belongs_to :user end diff --git a/spec/support/models/short_quiz.rb b/spec/support/models/short_quiz.rb index e6c585167b..fdae61ac1b 100644 --- a/spec/support/models/short_quiz.rb +++ b/spec/support/models/short_quiz.rb @@ -3,5 +3,5 @@ class ShortQuiz include Mongoid::Document include Mongoid::Timestamps::Created::Short - field :name, type: String + field :name, type: :string end diff --git a/spec/support/models/simple.rb b/spec/support/models/simple.rb index d5e1fbf6ba..8657baaf34 100644 --- a/spec/support/models/simple.rb +++ b/spec/support/models/simple.rb @@ -2,6 +2,6 @@ class Simple include Mongoid::Document - field :name, type: String + field :name, type: :string scope :nothing, -> { none } end diff --git a/spec/support/models/sound.rb b/spec/support/models/sound.rb index 1440ec1489..05b6748e40 100644 --- a/spec/support/models/sound.rb +++ b/spec/support/models/sound.rb @@ -2,6 +2,6 @@ class Sound include Mongoid::Document - field :active, type: Mongoid::Boolean + field :active, type: :boolean default_scope ->{ where(active: true) } end diff --git a/spec/support/models/square.rb b/spec/support/models/square.rb index 51adcd8b19..326f1bddfb 100644 --- a/spec/support/models/square.rb +++ b/spec/support/models/square.rb @@ -1,6 +1,6 @@ # frozen_string_literal: true class Square < Shape - field :width, type: Integer, default: 0 - field :height, type: Integer, default: 0 + field :width, type: :integer, default: 0 + field :height, type: :integer, default: 0 end diff --git a/spec/support/models/staff.rb b/spec/support/models/staff.rb index c661b2695c..b241ff9eb3 100644 --- a/spec/support/models/staff.rb +++ b/spec/support/models/staff.rb @@ -5,5 +5,5 @@ class Staff embedded_in :company - field :age, type: Integer + field :age, type: :integer end diff --git a/spec/support/models/subscription.rb b/spec/support/models/subscription.rb index 6868ab6361..ed3ad7124f 100644 --- a/spec/support/models/subscription.rb +++ b/spec/support/models/subscription.rb @@ -3,5 +3,5 @@ class Subscription include Mongoid::Document has_many :packs, class_name: "ShippingPack" - field :packs_count, type: Integer + field :packs_count, type: :integer end diff --git a/spec/support/models/symptom.rb b/spec/support/models/symptom.rb index 68f392ff51..bc2f34529f 100644 --- a/spec/support/models/symptom.rb +++ b/spec/support/models/symptom.rb @@ -2,7 +2,7 @@ class Symptom include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :person default_scope ->{ asc(:name) } end diff --git a/spec/support/models/tag.rb b/spec/support/models/tag.rb index 8e25946fc2..fc36a2a17f 100644 --- a/spec/support/models/tag.rb +++ b/spec/support/models/tag.rb @@ -2,7 +2,7 @@ class Tag include Mongoid::Document - field :text, type: String + field :text, type: :string has_and_belongs_to_many :actors has_and_belongs_to_many :articles has_and_belongs_to_many :posts diff --git a/spec/support/models/target.rb b/spec/support/models/target.rb index 7c2e77ed30..b4971a5f16 100644 --- a/spec/support/models/target.rb +++ b/spec/support/models/target.rb @@ -2,6 +2,6 @@ class Target include Mongoid::Document - field :name, type: String + field :name, type: :string embedded_in :targetable, polymorphic: true end diff --git a/spec/support/models/template.rb b/spec/support/models/template.rb index 4f20932985..df1dbb137b 100644 --- a/spec/support/models/template.rb +++ b/spec/support/models/template.rb @@ -2,6 +2,6 @@ class Template include Mongoid::Document - field :active, type: Mongoid::Boolean, default: false + field :active, type: :boolean, default: false validates :active, presence: true end diff --git a/spec/support/models/topping.rb b/spec/support/models/topping.rb index d424adfd97..7f1f2bc0b2 100644 --- a/spec/support/models/topping.rb +++ b/spec/support/models/topping.rb @@ -2,6 +2,6 @@ class Topping include Mongoid::Document - field :name, type: String + field :name, type: :string belongs_to :pizza end diff --git a/spec/support/models/track.rb b/spec/support/models/track.rb index dadf33b9cb..140da853df 100644 --- a/spec/support/models/track.rb +++ b/spec/support/models/track.rb @@ -2,13 +2,13 @@ class Track include Mongoid::Document - field :name, type: String + field :name, type: :string - field :before_create_called, type: Mongoid::Boolean, default: false - field :before_save_called, type: Mongoid::Boolean, default: false - field :before_update_called, type: Mongoid::Boolean, default: false - field :before_validation_called, type: Mongoid::Boolean, default: false - field :before_destroy_called, type: Mongoid::Boolean, default: false + field :before_create_called, type: :boolean, default: false + field :before_save_called, type: :boolean, default: false + field :before_update_called, type: :boolean, default: false + field :before_validation_called, type: :boolean, default: false + field :before_destroy_called, type: :boolean, default: false embedded_in :record diff --git a/spec/support/models/tree.rb b/spec/support/models/tree.rb index 0cb8aea035..26050b59b7 100644 --- a/spec/support/models/tree.rb +++ b/spec/support/models/tree.rb @@ -4,7 +4,7 @@ class Tree include Mongoid::Document field :name - field :evergreen, type: Mongoid::Boolean + field :evergreen, type: :boolean scope :verdant, ->{ where(evergreen: true) } default_scope ->{ asc(:name) } diff --git a/spec/support/models/truck.rb b/spec/support/models/truck.rb index 21382c6310..a396b8d8ff 100644 --- a/spec/support/models/truck.rb +++ b/spec/support/models/truck.rb @@ -3,5 +3,5 @@ class Truck < Vehicle embeds_one :bed - field :capacity, type: Integer + field :capacity, type: :integer end diff --git a/spec/support/models/updatable.rb b/spec/support/models/updatable.rb index 041926af5e..05b62a93d8 100644 --- a/spec/support/models/updatable.rb +++ b/spec/support/models/updatable.rb @@ -3,5 +3,5 @@ class Updatable include Mongoid::Document - field :updated_at, type: BSON::Timestamp + field :updated_at, type: :bson_timestamp end diff --git a/spec/support/models/user.rb b/spec/support/models/user.rb index fc831d057c..e0c7d83420 100644 --- a/spec/support/models/user.rb +++ b/spec/support/models/user.rb @@ -4,8 +4,8 @@ class User include Mongoid::Document field :name - field :last_login, type: DateTime - field :account_expires, type: Date + field :last_login, type: :date_time + field :account_expires, type: :date has_one :account, foreign_key: :creator_id, validate: false has_many :posts, foreign_key: :author_id, validate: false diff --git a/spec/support/models/user_account.rb b/spec/support/models/user_account.rb index 0997103951..e8f6af0f8f 100644 --- a/spec/support/models/user_account.rb +++ b/spec/support/models/user_account.rb @@ -2,9 +2,9 @@ class UserAccount include Mongoid::Document - field :username, type: String - field :name, type: String - field :email, type: String + field :username, type: :string + field :name, type: :string + field :email, type: :string validates_uniqueness_of :username, message: "is not unique" validates_uniqueness_of :email, message: "is not unique", case_sensitive: false validates_length_of :name, minimum: 2, allow_nil: true diff --git a/spec/support/models/validation_callback.rb b/spec/support/models/validation_callback.rb index 32aa38ebe8..a9f3c238c2 100644 --- a/spec/support/models/validation_callback.rb +++ b/spec/support/models/validation_callback.rb @@ -2,7 +2,7 @@ class ValidationCallback include Mongoid::Document - field :history, type: Array, default: [] + field :history, type: :array, default: [] validate do self.history << :validate end diff --git a/spec/support/models/version.rb b/spec/support/models/version.rb index ccb4c19220..d7b92b73b8 100644 --- a/spec/support/models/version.rb +++ b/spec/support/models/version.rb @@ -2,6 +2,6 @@ class Version include Mongoid::Document - field :number, type: Integer + field :number, type: :integer embedded_in :memorable, polymorphic: true end diff --git a/spec/support/models/vet_visit.rb b/spec/support/models/vet_visit.rb index ec2ec13c7d..83b89f18e5 100644 --- a/spec/support/models/vet_visit.rb +++ b/spec/support/models/vet_visit.rb @@ -2,6 +2,6 @@ class VetVisit include Mongoid::Document - field :date, type: Date + field :date, type: :date embedded_in :pet end diff --git a/spec/support/models/video.rb b/spec/support/models/video.rb index 0a6f37ba2f..d1e2a12f12 100644 --- a/spec/support/models/video.rb +++ b/spec/support/models/video.rb @@ -2,10 +2,10 @@ class Video include Mongoid::Document - field :title, type: String - field :year, type: Integer - field :release_dates, type: Set - field :genres, type: Array + field :title, type: :string + field :year, type: :integer + field :release_dates, type: :set + field :genres, type: :array embedded_in :person belongs_to :post diff --git a/spec/support/models/wiki_page.rb b/spec/support/models/wiki_page.rb index 6ab08fb106..fd443d2f6b 100644 --- a/spec/support/models/wiki_page.rb +++ b/spec/support/models/wiki_page.rb @@ -4,10 +4,10 @@ class WikiPage include Mongoid::Document include Mongoid::Timestamps - field :title, type: String - field :transient_property, type: String - field :author, type: String - field :description, type: String, localize: true + field :title, type: :string + field :transient_property, type: :string + field :author, type: :string + field :description, type: :string, localize: true embeds_many :edits, validate: false # Must have dependent: :destroy diff --git a/spec/support/models/word.rb b/spec/support/models/word.rb index 07a8ab47fd..3d3e68dd4b 100644 --- a/spec/support/models/word.rb +++ b/spec/support/models/word.rb @@ -2,8 +2,8 @@ class Word include Mongoid::Document - field :name, type: String - field :origin, type: String + field :name, type: :string + field :origin, type: :string belongs_to :dictionary diff --git a/spec/support/models/word_origin.rb b/spec/support/models/word_origin.rb index 87eb2935cf..c6d648438b 100644 --- a/spec/support/models/word_origin.rb +++ b/spec/support/models/word_origin.rb @@ -3,11 +3,11 @@ class WordOrigin include Mongoid::Document - field :_id, type: Integer, overwrite: true, default: ->{ origin_id } + field :_id, type: :integer, overwrite: true, default: ->{ origin_id } - field :origin_id, type: Integer - field :country, type: String - field :city, type: String + field :origin_id, type: :integer + field :country, type: :string + field :city, type: :string embedded_in :word end diff --git a/spec/support/models/writer.rb b/spec/support/models/writer.rb index 719829296b..db3bc25eb5 100644 --- a/spec/support/models/writer.rb +++ b/spec/support/models/writer.rb @@ -2,7 +2,7 @@ class Writer include Mongoid::Document - field :speed, type: Integer, default: 0 + field :speed, type: :integer, default: 0 embedded_in :canvas From 22222c62737b07bd5922ac8c1464b17209b0f5e8 Mon Sep 17 00:00:00 2001 From: shields Date: Tue, 5 Apr 2022 22:37:05 +0900 Subject: [PATCH 10/14] - Prefer defining field type value as a Symbol rather than a Class. (Symbol is already supported today.) - Deprecate using field type as a Class. - Add ability to define custom field types using a mini DSL (Mongoid::Fields.configure) - Fix Mongoid::Fields.option documentation --- docs/reference/fields.txt | 125 ++++++++------- docs/release-notes/mongoid-8.0.txt | 37 +++++ lib/config/locales/en.yml | 22 ++- lib/mongoid/errors.rb | 1 + lib/mongoid/errors/invalid_field_type.rb | 25 +++ lib/mongoid/fields.rb | 63 ++++---- lib/mongoid/fields/field_types.rb | 83 ++++++++++ .../mongoid/errors/invalid_field_type_spec.rb | 31 ++++ spec/mongoid/fields/field_types_spec.rb | 148 ++++++++++++++++++ spec/mongoid/fields_spec.rb | 148 ++++++++++-------- 10 files changed, 535 insertions(+), 148 deletions(-) create mode 100644 lib/mongoid/errors/invalid_field_type.rb create mode 100644 lib/mongoid/fields/field_types.rb create mode 100644 spec/mongoid/errors/invalid_field_type_spec.rb create mode 100644 spec/mongoid/fields/field_types_spec.rb diff --git a/docs/reference/fields.txt b/docs/reference/fields.txt index 0c96e7b988..3160b672cb 100644 --- a/docs/reference/fields.txt +++ b/docs/reference/fields.txt @@ -55,34 +55,40 @@ on a person by using the ``field`` macro. class Person include Mongoid::Document - field :name, type: String - field :date_of_birth, type: Date - field :weight, type: Float + field :name, type: :string + field :date_of_birth, type: :date + field :weight, type: :float end Below is a list of valid types for fields. -- ``Array`` -- ``BigDecimal`` -- ``Boolean`` -- ``Date`` -- ``DateTime`` -- ``Float`` -- ``Hash`` -- ``Integer`` -- ``BSON::ObjectId`` -- ``BSON::Binary`` -- ``Range`` -- ``Regexp`` -- ``Set`` -- ``String`` -- ``StringifiedSymbol`` -- ``Symbol`` -- ``Time`` -- ``TimeWithZone`` +- ``:array`` +- ``:big_decimal`` +- ``:boolean`` +- ``:date`` +- ``:date_time`` +- ``:decimal128`` (uses ``BSON::Decimal128``) +- ``:float`` +- ``:hash`` +- ``:integer`` +- ``:object_id`` (uses ``BSON::ObjectID``) +- ``:binary`` (uses ``BSON::Binary``) +- ``:range`` +- ``:regexp`` +- ``:set`` +- ``:string`` +- ``:stringified_symbol`` (see below) +- ``:symbol`` +- ``:time`` +- ``:time_with_zone`` To define custom field types, refer to :ref:`Custom Field Types ` below. +As of Mongoid 8.0, ``field :type`` should be specified as a ``Symbol``. +Specifying as a ``Class`` is deprecated and will be no longer supported in a +future major version of Mongoid. Unrecognized field type symbols will result +in an `InvalidFieldType` error when the model class is loaded. + .. _omitting-field-type-definition: @@ -116,16 +122,16 @@ Types that are not supported as dynamic attributes since they cannot be cast are .. _field-type-stringified-symbol: -Field Type: StringifiedSymbol ------------------------------ +Field Type :stringified_symbol +------------------------------ -The ``StringifiedSymbol`` field type is the recommended field type for storing -values that should be exposed as symbols to Ruby applications. When using the ``Symbol`` field type, +The ``:stringified_symbol`` field type is the recommended field type for storing +values that should be exposed as symbols to Ruby applications. When using the ``:symbol`` field type, Mongoid defaults to storing values as BSON symbols. For more information on the BSON symbol type, see :ref:`here `. However, the BSON symbol type is deprecated and is difficult to work with in programming languages -without native symbol types, so the ``StringifiedSymbol`` type allows the use of symbols -while ensuring interoperability with other drivers. The ``StringifiedSymbol`` type stores all data +without native symbol types, so the ``:stringified_symbol`` type allows the use of symbols +while ensuring interoperability with other drivers. The ``:stringified_symbol`` type stores all data on the database as strings, while exposing values to the application as symbols. An example usage is shown below: @@ -170,15 +176,15 @@ migration from fields that currently store either strings or BSON symbols in the .. _field-type-symbol: -Field Type: Symbol +Field Type :symbol ------------------ -New applications should use the :ref:`StringifiedSymbol field type ` -to store Ruby symbols in the database. The ``StringifiedSymbol`` field type +New applications should use the :ref:`:stringified_symbol field type ` +to store Ruby symbols in the database. The ``:stringified_symbol`` field type provides maximum compatibility with other applications and programming languages and has the same behavior in all circumstances. -Mongoid also provides the deprecated ``Symbol`` field type for serializing +Mongoid also provides the deprecated ``:symbol`` field type for serializing Ruby symbols to BSON symbols. Because the BSON specification deprecated the BSON symbol type, the `bson` gem will serialize Ruby symbols into BSON strings when used on its own. However, in order to maintain backwards compatibility @@ -201,10 +207,10 @@ snippet in your project: .. _field-type-hash: -Field Type: Hash +Field Type :hash ---------------- -When using a field of type Hash, be wary of adhering to the +When using a field of type ``:hash``, be wary of adhering to the `legal key names for mongoDB `_, or else the values will not store properly. @@ -213,7 +219,7 @@ or else the values will not store properly. class Person include Mongoid::Document field :first_name - field :url, type: Hash + field :url, type: :hash # will update the fields properly and save the values def set_vals @@ -233,21 +239,21 @@ or else the values will not store properly. .. _field-type-time: -Field Type: Time +Field Type :time ---------------- -``Time`` fields store values as ``Time`` instances in the :ref:`configured +``:time`` fields store values as ``Time`` instances in the :ref:`configured time zone `. ``Date`` and ``DateTime`` instances are converted to ``Time`` instances upon -assignment to a ``Time`` field: +assignment to a ``:time`` field: .. code-block:: ruby class Voter include Mongoid::Document - - field :registered_at, type: Time + + field :registered_at, type: :time end Voter.new(registered_at: Date.today) @@ -259,10 +265,10 @@ local time, because the application was not configured to use UTC times. .. _field-type-date: -Field Type: Date +Field Type :date ---------------- -Mongoid allows assignment of values of several types to ``Date`` fields: +Mongoid allows assignment of values of several types to ``:date`` fields: - ``Date`` - the provided date is stored as is. - ``Time``, ``DateTime``, ``ActiveSupport::TimeWithZone`` - the date component @@ -280,20 +286,20 @@ As a date & time to date conversion is lossy (it discards the time component), especially if an application operates with times in different time zones it is recommended to explicitly convert ``String``, ``Time`` and ``DateTime`` objects to ``Date`` objects before assigning the values to fields of type -``Date``. +``:date``. .. _field-type-date-time: -Field Type: DateTime +Field Type :date_time --------------------- MongoDB stores all times as UTC timestamps. When assigning a value to a -``DateTime`` field, or when querying a ``DateTime`` field, Mongoid +``:date_time`` field, or when querying a ``:date_time`` field, Mongoid converts the passed in value to a UTC ``Time`` before sending it to the MongoDB server. -``Time``, ``ActiveSupport::TimeWithZone`` and ``DateTime`` objects embed +``Time``, ``ActiveSupport::TimeWithZone``, and ``DateTime`` objects embed time zone information, and the value persisted is the specified moment in time, in UTC. When the value is retrieved, the time zone in which it is returned is defined by the :ref:`configured time zone settings `. @@ -302,7 +308,7 @@ returned is defined by the :ref:`configured time zone settings `. class Ticket include Mongoid::Document - field :opened_at, type: DateTime + field :opened_at, type: :date_time end Mongoid.use_activesupport_time_zone = true @@ -332,7 +338,7 @@ doing so, the integers/floats are assumed to be Unix timestamps (in UTC): ticket.opened_at # => Fri, 14 Dec 2018 16:12:54 +0000 -If a string is used as a ``DateTime`` field value, the behavior depends on +If a ``String`` is used as a ``:date_time`` field value, the behavior depends on whether the string includes a time zone. If no time zone is specified, the :ref:`default Mongoid time zone ` is used: @@ -354,7 +360,7 @@ If a time zone is specified, it is respected: .. _field-type-regexp: -Field Type: Regexp +Field Type :regexp ------------------ MongoDB supports storing regular expressions in documents, and querying using @@ -365,7 +371,7 @@ fork of `Oniguruma regular expression engine The two regular expression implementations generally provide equivalent functionality but have several important syntax differences. -When a field is declared to be of type Regexp, Mongoid converts Ruby regular +When a field is declared to be of type ``:regexp``, Mongoid converts Ruby regular expressions to BSON regular expressions and stores the result in MongoDB. Retrieving the field from the database produces a ``BSON::Regexp::Raw`` instance: @@ -375,7 +381,7 @@ instance: class Token include Mongoid::Document - field :pattern, type: Regexp + field :pattern, type: :regexp end token = Token.create!(pattern: /hello.world/m) @@ -847,9 +853,20 @@ can use in our model class as follows: class Profile include Mongoid::Document - field :location, type: Point + field :location, type: :point + end + +First, declare the new field type mapping in an initializer: + +.. code-block:: ruby + + # in /config/initializers/mongoid_custom_fields.rb + + Mongoid::Fields.configure do + type :point, Point end + Then make a Ruby class to represent the type. This class must define methods used for MongoDB serialization and deserialization as follows: @@ -945,8 +962,10 @@ specifiying its handler function as a block: # in /config/initializers/mongoid_custom_fields.rb - Mongoid::Fields.option :required do |model, field, value| - model.validates_presence_of field if value + Mongoid::Fields.configure do + option :required do |model, field, value| + model.validates_presence_of field.name if value + end end Then, use it your model class: diff --git a/docs/release-notes/mongoid-8.0.txt b/docs/release-notes/mongoid-8.0.txt index ef2ddfce8d..cd1089093a 100644 --- a/docs/release-notes/mongoid-8.0.txt +++ b/docs/release-notes/mongoid-8.0.txt @@ -276,3 +276,40 @@ as well as ActiveRecord-compatible ``previously_new_record?`` and user.destroy user.previously_persisted? # => true + + +Setting Field Type as a Class is Deprecated +------------------------------------------- + +Mongoid has historically supported defining the ``field :type`` option +as either a Symbol or a Class. As of Mongoid 8.0, using a Class is deprecated +and Symbol is preferred. Support for ``field :type`` as a Class will be +removed in a future major version of Mongoid. + +.. code-block:: ruby + + class Person + include Mongoid::Document + + # Deprecated; will log an warning message. + field :first_name, type: String + + # Good + field :last_name, type: :string + end + + +Support for Defining Custom Field Type Values +--------------------------------------------- + +Mongoid 8.0 adds the ability to define custom ``field :type`` Symbol values as follows: + +.. code-block:: ruby + + # in /config/initializers/mongoid_custom_fields.rb + + Mongoid::Fields.configure do + type :point, Point + end + +Refer to the :ref:`docs ` for details. diff --git a/lib/config/locales/en.yml b/lib/config/locales/en.yml index 4942a5431d..0e00a818dc 100644 --- a/lib/config/locales/en.yml +++ b/lib/config/locales/en.yml @@ -172,8 +172,10 @@ en: resolution: "When defining the field :%{name} on '%{klass}', please provide valid options for the field. These are currently: %{valid}. If you meant to define a custom field option, please do so first as follows:\n\n - \_\_Mongoid::Fields.option :%{option} do |model, field, value|\n - \_\_\_\_# Your logic here...\n + \_\_Mongoid::Fields.configure do\n + \_\_\_\_option :%{option} do |model, field, value|\n + \_\_\_\_\_\_# Your logic here...\n + \_\_\_\_end\n \_\_end\n \_\_class %{klass}\n \_\_\_\_include Mongoid::Document\n @@ -181,6 +183,22 @@ en: \_\_end\n\n Refer to: https://docs.mongodb.com/mongoid/current/reference/fields/#custom-field-options" + invalid_field_type: + message: "Invalid field type :%{type} for field :%{field} on model '%{klass}'." + summary: "Model '%{klass}' defines a field :%{field} with an unknown :type value + :%{type}. This value is neither present in Mongoid's default type mapping, + nor defined in a custom field type mapping." + resolution: "Please provide a valid :type value for the field. If you + meant to define a custom field type, please do so first as follows:\n\n + \_\_Mongoid::Fields.configure do\n + \_\_\_\_type :%{type}, YourTypeClass + \_\_end\n + \_\_class %{klass}\n + \_\_\_\_include Mongoid::Document\n + \_\_\_\_field :%{field}, type: :%{type}\n + \_\_end\n\n + Refer to: + https://docs.mongodb.com/mongoid/current/reference/fields/#custom-field-types" invalid_includes: message: "Invalid includes directive: %{klass}.includes(%{args})" summary: "Eager loading in Mongoid only supports providing arguments diff --git a/lib/mongoid/errors.rb b/lib/mongoid/errors.rb index e530c54f88..dc36124e76 100644 --- a/lib/mongoid/errors.rb +++ b/lib/mongoid/errors.rb @@ -15,6 +15,7 @@ require "mongoid/errors/invalid_dependent_strategy" require "mongoid/errors/invalid_field" require "mongoid/errors/invalid_field_option" +require "mongoid/errors/invalid_field_type" require "mongoid/errors/invalid_find" require "mongoid/errors/invalid_includes" require "mongoid/errors/invalid_index" diff --git a/lib/mongoid/errors/invalid_field_type.rb b/lib/mongoid/errors/invalid_field_type.rb new file mode 100644 index 0000000000..403866d254 --- /dev/null +++ b/lib/mongoid/errors/invalid_field_type.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +module Mongoid + module Errors + + # This error is raised when trying to define a field using a :type option value + # that is not present in the field type mapping. + class InvalidFieldType < MongoidError + + # Create the new error. + # + # @example Instantiate the error. + # InvalidFieldType.new('Person', 'first_name', 'stringgy') + # + # @param [ String ] klass The model class. + # @param [ String ] field The field on which the invalid type is used. + # @param [ String ] type The value of the field :type option. + def initialize(klass, field, type) + super( + compose_message('invalid_field_type', { klass: klass, field: field, type: type }) + ) + end + end + end +end diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index f9efa2d500..f8ff0349be 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -4,6 +4,7 @@ require "mongoid/fields/foreign_key" require "mongoid/fields/localized" require "mongoid/fields/validators" +require "mongoid/fields/field_types" module Mongoid @@ -11,30 +12,10 @@ module Mongoid module Fields extend ActiveSupport::Concern + # @deprecated Remove class aliases in Mongoid 8.0. StringifiedSymbol = Mongoid::StringifiedSymbol Boolean = Mongoid::Boolean - # For fields defined with symbols use the correct class. - TYPE_MAPPINGS = { - array: Array, - big_decimal: BigDecimal, - binary: BSON::Binary, - boolean: Mongoid::Boolean, - date: Date, - date_time: DateTime, - float: Float, - hash: Hash, - integer: Integer, - object_id: BSON::ObjectId, - range: Range, - regexp: Regexp, - set: Set, - string: String, - stringified_symbol: StringifiedSymbol, - symbol: Symbol, - time: Time - }.with_indifferent_access - # Constant for all names of the _id field in a document. # # This does not include aliases of _id field. @@ -241,6 +222,27 @@ def using_object_ids? class << self + # DSL method used for configuration readability, typically in + # an initializer. + # + # @example + # Mongoid::Fields.configure do + # # do configuration + # end + def configure(&block) + instance_exec(&block) + end + + # Defines a field type mapping, for later use in field :type option. + # + # @example + # Mongoid::Fields.configure do + # type :point, Point + # end + def type(symbol, klass) + Fields::FieldTypes.define(symbol, klass) + end + # Stores the provided block to be run when the option name specified is # defined on a field. # @@ -249,8 +251,10 @@ class << self # provided in the field definition -- even if it is false or nil. # # @example - # Mongoid::Fields.option :required do |model, field, value| - # model.validates_presence_of field if value + # Mongoid::Fields.configure do + # option :required do |model, field, value| + # model.validates_presence_of field.name if value + # end # end # # @param [ Symbol ] option_name the option name to match against @@ -729,19 +733,16 @@ def remove_defaults(name) def field_for(name, options) opts = options.merge(klass: self) - type_mapping = TYPE_MAPPINGS[options[:type]] - opts[:type] = type_mapping || unmapped_type(options) + opts[:type] = field_type_klass_for(name, options[:type]) return Fields::Localized.new(name, opts) if options[:localize] return Fields::ForeignKey.new(name, opts) if options[:identity] Fields::Standard.new(name, opts) end - def unmapped_type(options) - if "Boolean" == options[:type].to_s - Mongoid::Boolean - else - options[:type] || Object - end + def field_type_klass_for(field, type) + klass = Fields::FieldTypes.get(type) + return klass if klass + raise Mongoid::Errors::InvalidFieldType.new(self.name, field, type) end end end diff --git a/lib/mongoid/fields/field_types.rb b/lib/mongoid/fields/field_types.rb new file mode 100644 index 0000000000..0ea0db02f4 --- /dev/null +++ b/lib/mongoid/fields/field_types.rb @@ -0,0 +1,83 @@ +# frozen_string_literal: true + +module Mongoid + module Fields + + # Singleton module which contains a cache for field type definitions. + # Custom field types can be configured. + module FieldTypes + extend self + + # For fields defined with symbols use the correct class. + DEFAULT_MAPPING = { + array: Array, + bigdecimal: BigDecimal, + big_decimal: BigDecimal, + binary: BSON::Binary, + boolean: Mongoid::Boolean, + date: Date, + datetime: DateTime, + date_time: DateTime, + decimal128: BSON::Decimal128, + double: Float, + float: Float, + hash: Hash, + integer: Integer, + object: Object, + object_id: BSON::ObjectId, + range: Range, + regexp: Regexp, + set: Set, + string: String, + stringified_symbol: Mongoid::StringifiedSymbol, + symbol: Symbol, + time: Time, + time_with_zone: ActiveSupport::TimeWithZone + }.with_indifferent_access.freeze + + def get(value) + value = value.to_sym if value.is_a?(String) + mapping[value] || handle_unmapped_type(value) + end + + def define(symbol, klass) + mapping[symbol.to_sym] = klass + end + + delegate :delete, to: :mapping + + private + + def mapping + @mapping ||= DEFAULT_MAPPING.dup + end + + def handle_unmapped_type(type) + return Object if type.nil? + + if type.is_a?(Module) + warn_class_type(type.name) + return Mongoid::Boolean if type.to_s == 'Boolean' + return type + end + + nil + end + + def warn_class_type(type) + return if warned_class_types.include?(type) + symbol = type.demodulize.underscore + Mongoid.logger.warn( + "Using a Class (#{type}) in the field :type option is deprecated " + + "and will be removed in a future major Mongoid version. " + + "Please use a Symbol (:#{symbol}) instead." + ) + warned_class_types << type + end + + def warned_class_types + @warned_class_types ||= [] + end + end + end +end diff --git a/spec/mongoid/errors/invalid_field_type_spec.rb b/spec/mongoid/errors/invalid_field_type_spec.rb new file mode 100644 index 0000000000..97aec11bdb --- /dev/null +++ b/spec/mongoid/errors/invalid_field_type_spec.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require "spec_helper" + +describe Mongoid::Errors::InvalidFieldType do + + describe "#message" do + + let(:error) do + described_class.new(Person, :first_name, :stringgy) + end + + it "contains the problem in the message" do + expect(error.message).to include( + "Invalid field type :stringgy for field :first_name on model 'Person'." + ) + end + + it "contains the summary in the message" do + expect(error.message).to include( + "Model 'Person' defines a field :first_name with an unknown :type value :stringgy." + ) + end + + it "contains the resolution in the message" do + expect(error.message).to include( + 'Please provide a valid :type value for the field. If you meant to define' + ) + end + end +end diff --git a/spec/mongoid/fields/field_types_spec.rb b/spec/mongoid/fields/field_types_spec.rb new file mode 100644 index 0000000000..cf8e32c026 --- /dev/null +++ b/spec/mongoid/fields/field_types_spec.rb @@ -0,0 +1,148 @@ +# frozen_string_literal: true + +require "spec_helper" + +describe Mongoid::Fields::FieldTypes do + + after do + described_class.instance_variable_set(:@mapping, described_class::DEFAULT_MAPPING.dup) + end + + describe '.get' do + subject { described_class.get(type) } + + context 'when value is a default mapped symbol' do + let(:type) { :float } + + it 'uses the default mapped type' do + is_expected.to eq Float + end + end + + context 'when value is a default mapped string' do + let(:type) { 'double' } + + it 'uses the default mapped type' do + is_expected.to eq Float + end + end + + context 'when value is a custom mapped symbol' do + before { described_class.define('number', Integer) } + let(:type) { :number } + + it 'uses the custom mapped type' do + is_expected.to eq Integer + end + end + + context 'when value is a custom mapped string' do + before { described_class.define(:number, Float) } + let(:type) { 'number' } + + it 'uses the custom mapped type' do + is_expected.to eq Float + end + end + + context 'when value is an unmapped symbol' do + let(:type) { :my_value } + + it 'returns nil' do + is_expected.to eq nil + end + end + + context 'when value is a unmapped string' do + let(:type) { 'my_value' } + + it 'returns nil' do + is_expected.to eq nil + end + end + + context 'when value is a module' do + let(:type) { String } + + it 'uses the module type' do + is_expected.to eq String + end + + context 'deprecation' do + around do |example| + old_types = described_class.instance_variable_get(:@warned_class_types) + described_class.instance_variable_set(:@warned_class_types, []) + example.run + described_class.instance_variable_set(:@warned_class_types, old_types) + end + + it 'warns deprecation for the class type once' do + expect(Mongoid.logger).to receive(:warn).once.with(match(/\AUsing a Class \(String\)/)) + described_class.get(String) + described_class.get(String) + expect(Mongoid.logger).to receive(:warn).once.with(match(/\AUsing a Class \(Integer\)/)) + described_class.get(Integer) + described_class.get(String) + described_class.get(Integer) + end + end + end + + context 'when value is the module Boolean' do + let(:type) do + stub_const('Boolean', Module.new) + Boolean + end + + it 'returns Mongoid::Boolean type' do + is_expected.to eq Mongoid::Boolean + end + end + + context 'when value is nil' do + let(:type) { nil } + + it 'returns Object type' do + is_expected.to eq Object + end + end + end + + describe '.define' do + + it 'can define a new type' do + described_class.define(:my_string, String) + expect(described_class.get(:my_string)).to eq String + end + + it 'can override a default type' do + described_class.define(:integer, String) + expect(described_class.get(:integer)).to eq String + end + + it 'does not alter the DEFAULT_MAPPING constant' do + described_class.define(:integer, String) + expect(described_class::DEFAULT_MAPPING[:integer]).to eq Integer + end + end + + describe '.delete' do + + it 'can delete a custom type' do + described_class.define(:my_string, String) + expect(described_class.get(:my_string)).to eq String + described_class.delete('my_string') + expect(described_class.get(:my_string)).to eq nil + end + + it 'can delete a default type' do + described_class.delete(:integer) + expect(described_class.get(:integer)).to eq nil + end + + it 'does not alter the DEFAULT_MAPPING constant' do + described_class.delete(:integer) + expect(described_class::DEFAULT_MAPPING[:integer]).to eq Integer + end + end +end diff --git a/spec/mongoid/fields_spec.rb b/spec/mongoid/fields_spec.rb index 7798f8fc11..72b4857554 100644 --- a/spec/mongoid/fields_spec.rb +++ b/spec/mongoid/fields_spec.rb @@ -330,68 +330,39 @@ end end - it "converts :array to Array" do - expect(klass.field(:test, type: :array).type).to be(Array) - end - - it "converts :big_decimal to BigDecimal" do - expect(klass.field(:test, type: :big_decimal).type).to be(BigDecimal) - end - - it "converts :binary to BSON::Binary" do - expect(klass.field(:test, type: :binary).type).to be(BSON::Binary) - end - - it "converts :boolean to Mongoid::Boolean" do - expect(klass.field(:test, type: :boolean).type).to be(Mongoid::Boolean) - end - - it "converts :date to Date" do - expect(klass.field(:test, type: :date).type).to be(Date) - end - - it "converts :date_time to DateTime" do - expect(klass.field(:test, type: :date_time).type).to be(DateTime) - end - - it "converts :float to Float" do - expect(klass.field(:test, type: :float).type).to be(Float) - end - - it "converts :hash to Hash" do - expect(klass.field(:test, type: :hash).type).to be(Hash) - end - - it "converts :integer to Integer" do - expect(klass.field(:test, type: :integer).type).to be(Integer) - end - - it "converts :object_id to BSON::ObjectId" do - expect(klass.field(:test, type: :object_id).type).to be(BSON::ObjectId) - end - - it "converts :range to Range" do - expect(klass.field(:test, type: :range).type).to be(Range) - end - - it "converts :regexp to Rexegp" do - expect(klass.field(:test, type: :regexp).type).to be(Regexp) - end - - it "converts :set to Set" do - expect(klass.field(:test, type: :set).type).to be(Set) - end - - it "converts :string to String" do - expect(klass.field(:test, type: :string).type).to be(String) - end - - it "converts :symbol to Symbol" do - expect(klass.field(:test, type: :symbol).type).to be(Symbol) - end - - it "converts :time to Time" do - expect(klass.field(:test, type: :time).type).to be(Time) + { + array: Array, + bigdecimal: BigDecimal, + big_decimal: BigDecimal, + binary: BSON::Binary, + boolean: Mongoid::Boolean, + date: Date, + datetime: DateTime, + date_time: DateTime, + decimal128: BSON::Decimal128, + double: Float, + float: Float, + hash: Hash, + integer: Integer, + object: Object, + object_id: BSON::ObjectId, + range: Range, + regexp: Regexp, + set: Set, + string: String, + stringified_symbol: Mongoid::StringifiedSymbol, + symbol: Symbol, + time: Time, + time_with_zone: ActiveSupport::TimeWithZone + }.each do |field_type, field_klass| + + it "converts Symbol :#{field_type} to #{field_klass}" do + expect(klass.field(:test, type: field_type).type).to be(field_klass) + end + + it "converts String \"#{field_type}\" to #{field_klass}" do + expect(klass.field(:test, type: field_type.to_s).type).to be(field_klass) + end end end @@ -1796,4 +1767,57 @@ class DiscriminatorChild2 < DiscriminatorParent end end end + + describe '.configure DSL' do + + context '.type method' do + after do + klass = Mongoid::Fields::FieldTypes + klass.instance_variable_set(:@mapping, klass::DEFAULT_MAPPING.dup) + end + + it 'can define a custom type' do + described_class.configure do + type :my_type, Integer + end + + expect(described_class::FieldTypes.get(:my_type)).to eq Integer + end + + it 'can override and existing type' do + described_class.configure do + type :integer, String + end + + expect(described_class::FieldTypes.get(:integer)).to eq String + end + end + + context '.option method' do + after do + described_class.instance_variable_set(:@options, {}) + end + + it 'can define a custom field option' do + described_class.configure do + option :my_required do |model, field, value| + model.validates_presence_of field.name if value + end + end + + klass = Class.new do + include Mongoid::Document + field :my_field, my_required: true + + def self.model_name + OpenStruct.new(human: 'Klass') + end + end + + instance = klass.new + expect(instance.valid?).to eq false + expect(instance.errors.full_messages).to eq ["My field can't be blank"] + end + end + end end From 6fe4343ea87dead3f2a1b7a343ccf79ba0ed4340 Mon Sep 17 00:00:00 2001 From: Johnny Shields Date: Wed, 4 May 2022 06:34:54 +0900 Subject: [PATCH 11/14] Revert change --- .../mongoid/errors/invalid_field_type_spec.rb | 44 ++++++++++++++----- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/spec/mongoid/errors/invalid_field_type_spec.rb b/spec/mongoid/errors/invalid_field_type_spec.rb index 97aec11bdb..9a2575f861 100644 --- a/spec/mongoid/errors/invalid_field_type_spec.rb +++ b/spec/mongoid/errors/invalid_field_type_spec.rb @@ -10,22 +10,46 @@ described_class.new(Person, :first_name, :stringgy) end - it "contains the problem in the message" do - expect(error.message).to include( - "Invalid field type :stringgy for field :first_name on model 'Person'." - ) + context 'when type is a symbol' do + let(:error) do + described_class.new(Person, :first_name, :stringgy) + end + + it "contains the problem in the message" do + expect(error.message).to include( + "Invalid field type :stringgy for field 'first_name' on model 'Person'." + ) + end + + it "contains the summary in the message" do + expect(error.message).to include( + "Model 'Person' defines a field 'first_name' with an unknown type value :stringgy." + ) + end end - it "contains the summary in the message" do - expect(error.message).to include( - "Model 'Person' defines a field :first_name with an unknown :type value :stringgy." - ) + context 'when type is a string' do + let(:error) do + described_class.new(Person, :first_name, 'stringgy') + end + + it "contains the problem in the message" do + expect(error.message).to include( + %q,Invalid field type "stringgy" for field 'first_name' on model 'Person'., + ) + end + + it "contains the summary in the message" do + expect(error.message).to include( + %q,Model 'Person' defines a field 'first_name' with an unknown type value "stringgy"., + ) + end end it "contains the resolution in the message" do expect(error.message).to include( - 'Please provide a valid :type value for the field. If you meant to define' + 'Please provide a valid :type value for the field.' ) end end -end + From 39d2988e70325601f92b9429d70a2a50878ca943 Mon Sep 17 00:00:00 2001 From: shields Date: Thu, 5 May 2022 09:17:38 +0900 Subject: [PATCH 12/14] Fix spec --- spec/mongoid/errors/invalid_field_type_spec.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/spec/mongoid/errors/invalid_field_type_spec.rb b/spec/mongoid/errors/invalid_field_type_spec.rb index 9a2575f861..1d1a63022c 100644 --- a/spec/mongoid/errors/invalid_field_type_spec.rb +++ b/spec/mongoid/errors/invalid_field_type_spec.rb @@ -17,13 +17,13 @@ it "contains the problem in the message" do expect(error.message).to include( - "Invalid field type :stringgy for field 'first_name' on model 'Person'." + "Invalid field type :stringgy for field :first_name on model 'Person'." ) end it "contains the summary in the message" do expect(error.message).to include( - "Model 'Person' defines a field 'first_name' with an unknown type value :stringgy." + "Model 'Person' defines a field :first_name with an unknown :type value :stringgy." ) end end @@ -35,13 +35,13 @@ it "contains the problem in the message" do expect(error.message).to include( - %q,Invalid field type "stringgy" for field 'first_name' on model 'Person'., + %q,Invalid field type "stringgy" for field :first_name on model 'Person'., ) end it "contains the summary in the message" do expect(error.message).to include( - %q,Model 'Person' defines a field 'first_name' with an unknown type value "stringgy"., + %q,Model 'Person' defines a field :first_name with an unknown :type value "stringgy"., ) end end @@ -52,4 +52,4 @@ ) end end - +end From 6147e803d31de1f4d6a0ea9a84d4c17c872fee9a Mon Sep 17 00:00:00 2001 From: Johnny Shields Date: Thu, 5 May 2022 09:19:47 +0900 Subject: [PATCH 13/14] Update fields.rb --- lib/mongoid/fields.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/mongoid/fields.rb b/lib/mongoid/fields.rb index 3cbc0a2928..8fbe6e4e8e 100644 --- a/lib/mongoid/fields.rb +++ b/lib/mongoid/fields.rb @@ -12,7 +12,7 @@ module Mongoid module Fields extend ActiveSupport::Concern - # @deprecated Remove class aliases in Mongoid 8.0. + # @deprecated These class aliases should be removed in Mongoid 9.0. StringifiedSymbol = Mongoid::StringifiedSymbol Boolean = Mongoid::Boolean From 3a7128e00abbf08ae356a35b68e237b8efc8e8e1 Mon Sep 17 00:00:00 2001 From: shields Date: Thu, 5 May 2022 22:07:52 +0900 Subject: [PATCH 14/14] Fix spec --- spec/mongoid/fields_spec.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/spec/mongoid/fields_spec.rb b/spec/mongoid/fields_spec.rb index a0a3273a4c..3bac98e188 100644 --- a/spec/mongoid/fields_spec.rb +++ b/spec/mongoid/fields_spec.rb @@ -369,7 +369,7 @@ it 'raises InvalidFieldType' do lambda do klass.field(:test, type: :bogus) - end.should raise_error(Mongoid::Errors::InvalidFieldType, /defines a field 'test' with an unknown type value :bogus/) + end.should raise_error(Mongoid::Errors::InvalidFieldType, /defines a field :test with an unknown :type value :bogus/) end end @@ -377,7 +377,7 @@ it 'raises InvalidFieldType' do lambda do klass.field(:test, type: 'bogus') - end.should raise_error(Mongoid::Errors::InvalidFieldType, /defines a field 'test' with an unknown type value "bogus"/) + end.should raise_error(Mongoid::Errors::InvalidFieldType, /defines a field :test with an unknown :type value "bogus"/) end end end