diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0fde582ae..6f702d406 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -98,28 +98,28 @@ jobs: # JRuby - ruby: jruby-9.4 - gemfile: gemfiles/rails_7.0.gemfile + gemfile: gemfiles/rails_7.1.gemfile mongodb: '6.0' topology: replica_set - ruby: jruby-9.4 - gemfile: gemfiles/rails_6.0.gemfile + gemfile: gemfiles/rails_6.1.gemfile mongodb: '5.0' topology: server # Field-Level Encryption # TODO: support LIBMONGOCRYPT via path - ruby: ruby-3.2 - gemfile: gemfiles/rails_7.0.gemfile + gemfile: gemfiles/rails_7.1.gemfile mongodb: '6.0' topology: sharded_cluster fle: helper - ruby: ruby-3.1 - gemfile: gemfiles/rails_6.1.gemfile + gemfile: gemfiles/rails_7.0.gemfile mongodb: '6.0' topology: replica_set fle: helper - ruby: ruby-2.7 - gemfile: gemfiles/rails_6.0.gemfile + gemfile: gemfiles/rails_6.1.gemfile mongodb: '6.0' topology: server fle: helper diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index c9573dfd4..8b95d8ee4 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -1,11 +1,26 @@ # This configuration was generated by # `rubocop --auto-gen-config --exclude-limit 1000` -# on 2023-08-26 19:42:04 UTC using RuboCop version 1.49.0. +# on 2024-01-16 04:19:18 UTC using RuboCop version 1.60.0. # The point is for the user to remove these configuration records # one by one as the offenses are removed from the code base. # Note that changes in the inspected code, or installation of new # versions of RuboCop, may require this file to be generated again. +# Offense count: 1 +# Configuration parameters: EnforcedStyle, AllowedGems, Include. +# SupportedStyles: Gemfile, gems.rb, gemspec +# Include: **/*.gemspec, **/Gemfile, **/gems.rb +Gemspec/DevelopmentDependencies: + Exclude: + - 'mongoid.gemspec' + +# Offense count: 4 +Lint/SelfAssignment: + Exclude: + - 'spec/integration/associations/embeds_one_spec.rb' + - 'spec/integration/associations/has_one_spec.rb' + - 'spec/mongoid/association/embedded/embeds_one/proxy_spec.rb' + # Offense count: 108 # Configuration parameters: AllowedMethods, AllowedPatterns, CountRepeatedAttributes. Metrics/AbcSize: @@ -25,19 +40,19 @@ Metrics/BlockNesting: # Offense count: 17 # Configuration parameters: CountComments, CountAsOne. Metrics/ClassLength: - Max: 327 + Max: 337 -# Offense count: 50 +# Offense count: 51 # Configuration parameters: AllowedMethods, AllowedPatterns. Metrics/CyclomaticComplexity: Max: 33 -# Offense count: 182 +# Offense count: 184 # Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns. Metrics/MethodLength: Max: 87 -# Offense count: 21 +# Offense count: 22 # Configuration parameters: CountComments, CountAsOne. Metrics/ModuleLength: Max: 330 @@ -53,13 +68,13 @@ Metrics/ParameterLists: Metrics/PerceivedComplexity: Max: 20 -# Offense count: 3 +# Offense count: 2 +# This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyleForLeadingUnderscores. # SupportedStylesForLeadingUnderscores: disallowed, required, optional Naming/MemoizedInstanceVariableName: Exclude: - 'lib/mongoid/association/relatable.rb' - - 'lib/mongoid/document.rb' # Offense count: 27 RSpec/AnyInstance: @@ -80,7 +95,7 @@ RSpec/AnyInstance: RSpec/BeforeAfterAll: Enabled: false -# Offense count: 833 +# Offense count: 832 # Configuration parameters: Prefixes, AllowedPatterns. # Prefixes: when, with, without RSpec/ContextWording: @@ -176,7 +191,6 @@ RSpec/ContextWording: - 'spec/mongoid/errors/invalid_collection_spec.rb' - 'spec/mongoid/errors/invalid_includes_spec.rb' - 'spec/mongoid/extensions/date_class_mongoize_spec.rb' - - 'spec/mongoid/extensions/hash_spec.rb' - 'spec/mongoid/extensions/range_spec.rb' - 'spec/mongoid/fields/localized_spec.rb' - 'spec/mongoid/fields_spec.rb' @@ -203,7 +217,7 @@ RSpec/ContextWording: - 'spec/support/immutable_ids.rb' - 'spec/support/shared/time.rb' -# Offense count: 58 +# Offense count: 60 # Configuration parameters: IgnoredMetadata. RSpec/DescribeClass: Exclude: @@ -248,7 +262,7 @@ RSpec/DescribeClass: - 'spec/mongoid/railties/console_sandbox_spec.rb' - 'spec/mongoid/tasks/database_rake_spec.rb' -# Offense count: 126 +# Offense count: 124 RSpec/ExpectInHook: Exclude: - 'spec/integration/associations/embedded_spec.rb' @@ -291,7 +305,7 @@ RSpec/ExpectInHook: - 'spec/mongoid/validatable/presence_spec.rb' - 'spec/support/immutable_ids.rb' -# Offense count: 25 +# Offense count: 24 # Configuration parameters: Include, CustomTransform, IgnoreMethods, SpecSuffixOnly. # Include: **/*_spec*rb*, **/spec/**/* RSpec/FilePath: @@ -313,7 +327,6 @@ RSpec/FilePath: - 'spec/mongoid/extensions/raw_value_spec.rb' - 'spec/mongoid/extensions/stringified_symbol_spec.rb' - 'spec/mongoid/loading_spec.rb' - - 'spec/mongoid/railties/bson_object_id_serializer_spec.rb' - 'spec/mongoid/validatable/associated_spec.rb' - 'spec/mongoid/validatable/format_spec.rb' - 'spec/mongoid/validatable/length_spec.rb' @@ -335,7 +348,7 @@ RSpec/IteratedExpectation: - 'spec/mongoid/findable_spec.rb' - 'spec/mongoid_spec.rb' -# Offense count: 230 +# Offense count: 231 RSpec/LeakyConstantDeclaration: Exclude: - 'spec/integration/active_job_spec.rb' @@ -394,7 +407,7 @@ RSpec/LeakyConstantDeclaration: - 'spec/mongoid/validatable/numericality_spec.rb' - 'spec/mongoid/validatable/uniqueness_spec.rb' -# Offense count: 499 +# Offense count: 501 RSpec/LetSetup: Exclude: - 'spec/integration/matcher_examples_spec.rb' @@ -468,8 +481,8 @@ RSpec/LetSetup: - 'spec/mongoid/touchable_spec.rb' - 'spec/mongoid/validatable/uniqueness_spec.rb' -# Offense count: 298 -# Configuration parameters: EnforcedStyle. +# Offense count: 308 +# Configuration parameters: . # SupportedStyles: have_received, receive RSpec/MessageSpies: EnforcedStyle: receive @@ -481,7 +494,7 @@ RSpec/MultipleDescribes: - 'spec/mongoid/association/embedded/dirty_spec.rb' - 'spec/mongoid/tasks/database_rake_spec.rb' -# Offense count: 233 +# Offense count: 244 # Configuration parameters: EnforcedStyle, IgnoreSharedExamples. # SupportedStyles: always, named_only RSpec/NamedSubject: @@ -498,12 +511,12 @@ RSpec/NamedSubject: - 'spec/mongoid/extensions/raw_value_spec.rb' - 'spec/mongoid/matcher/expression_spec.rb' -# Offense count: 5025 +# Offense count: 5074 # Configuration parameters: AllowedGroups. RSpec/NestedGroups: Max: 13 -# Offense count: 37 +# Offense count: 31 # Configuration parameters: AllowedPatterns. # AllowedPatterns: ^expect_, ^assert_ RSpec/NoExpectationExample: @@ -516,7 +529,6 @@ RSpec/NoExpectationExample: - 'spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb' - 'spec/mongoid/attributes_spec.rb' - 'spec/mongoid/collection_configurable_spec.rb' - - 'spec/mongoid/criteria/queryable/storable_spec.rb' - 'spec/mongoid/document_spec.rb' - 'spec/mongoid/errors/mongoid_error_spec.rb' - 'spec/mongoid/persistence_context_spec.rb' @@ -638,7 +650,7 @@ RSpec/ScatteredSetup: - 'spec/mongoid/copyable_spec.rb' - 'spec/mongoid/persistable/deletable_spec.rb' -# Offense count: 14 +# Offense count: 12 RSpec/StubbedMock: Exclude: - 'spec/mongoid/clients_spec.rb' @@ -648,7 +660,7 @@ RSpec/StubbedMock: - 'spec/mongoid/tasks/encryption_spec.rb' - 'spec/mongoid/validatable/associated_spec.rb' -# Offense count: 21 +# Offense count: 26 RSpec/SubjectDeclaration: Exclude: - 'spec/integration/associations/embedded_dirty_spec.rb' @@ -656,7 +668,7 @@ RSpec/SubjectDeclaration: - 'spec/mongoid/collection_configurable_spec.rb' - 'spec/mongoid/contextual/mongo/documents_loader_spec.rb' -# Offense count: 28 +# Offense count: 27 # Configuration parameters: IgnoreNameless, IgnoreSymbolicNames. RSpec/VerifiedDoubles: Exclude: @@ -670,7 +682,6 @@ RSpec/VerifiedDoubles: - 'spec/mongoid/contextual/mongo/documents_loader_spec.rb' - 'spec/mongoid/errors/validations_spec.rb' - 'spec/mongoid/persistence_context_spec.rb' - - 'spec/mongoid/tasks/database_rake_spec.rb' - 'spec/mongoid/tasks/database_spec.rb' - 'spec/mongoid/threaded_spec.rb' - 'spec/mongoid/validatable/associated_spec.rb' @@ -688,7 +699,7 @@ Rails/Date: - 'spec/mongoid/persistable/maxable_spec.rb' - 'spec/mongoid/persistable/minable_spec.rb' -# Offense count: 21 +# Offense count: 20 # This cop supports safe autocorrection (--autocorrect). # Configuration parameters: EnforceForPrefixed. Rails/Delegate: @@ -700,7 +711,6 @@ Rails/Delegate: - 'lib/mongoid/clients/options.rb' - 'lib/mongoid/contextual/memory.rb' - 'lib/mongoid/contextual/none.rb' - - 'lib/mongoid/criteria.rb' - 'lib/mongoid/document.rb' - 'lib/mongoid/extensions/nil_class.rb' - 'lib/mongoid/extensions/symbol.rb' @@ -727,7 +737,7 @@ Rails/I18nLocaleAssignment: - 'spec/mongoid/validatable/uniqueness_spec.rb' - 'spec/support/macros.rb' -# Offense count: 129 +# Offense count: 133 # Configuration parameters: ForbiddenMethods, AllowedMethods. # ForbiddenMethods: decrement!, decrement_counter, increment!, increment_counter, insert, insert!, insert_all, insert_all!, toggle!, touch, touch_all, update_all, update_attribute, update_column, update_columns, update_counters, upsert, upsert_all Rails/SkipsModelValidations: @@ -755,23 +765,17 @@ Rails/SkipsModelValidations: - 'spec/mongoid/touchable_spec.rb' - 'spec/support/models/server.rb' -# Offense count: 159 +# Offense count: 151 # This cop supports unsafe autocorrection (--autocorrect-all). # Configuration parameters: EnforcedStyle. # SupportedStyles: strict, flexible Rails/TimeZone: Exclude: - - 'lib/mongoid/criteria/queryable/extensions/date.rb' - 'lib/mongoid/criteria/queryable/extensions/string.rb' - - 'lib/mongoid/extensions/array.rb' - 'lib/mongoid/extensions/date.rb' - - 'lib/mongoid/extensions/float.rb' - - 'lib/mongoid/extensions/integer.rb' - 'lib/mongoid/extensions/string.rb' - 'lib/mongoid/extensions/time.rb' - - 'lib/mongoid/timestamps/created.rb' - 'lib/mongoid/timestamps/updated.rb' - - 'lib/mongoid/touchable.rb' - 'spec/integration/criteria/date_field_spec.rb' - 'spec/integration/criteria/raw_value_spec.rb' - 'spec/integration/persistence/range_field_spec.rb' @@ -800,6 +804,17 @@ Rails/TimeZone: - 'spec/mongoid/touchable_spec.rb' - 'spec/support/models/post.rb' +# Offense count: 4 +# This cop supports safe autocorrection (--autocorrect). +# Configuration parameters: AllowOnlyRestArgument, UseAnonymousForwarding, RedundantRestArgumentNames, RedundantKeywordRestArgumentNames, RedundantBlockArgumentNames. +# RedundantRestArgumentNames: args, arguments +# RedundantKeywordRestArgumentNames: kwargs, options, opts +# RedundantBlockArgumentNames: blk, block, proc +Style/ArgumentsForwarding: + Exclude: + - 'lib/mongoid/association/referenced/has_many/enumerable.rb' + - 'lib/mongoid/association/referenced/has_many/proxy.rb' + # Offense count: 5 Style/MultilineBlockChain: Exclude: @@ -834,7 +849,55 @@ Style/OptionalBooleanParameter: - 'spec/support/models/address.rb' - 'spec/support/models/name.rb' -# Offense count: 240 +# Offense count: 38 +# This cop supports safe autocorrection (--autocorrect). +Style/RedundantCurrentDirectoryInPath: + Exclude: + - 'Gemfile' + - 'gemfiles/bson_master.gemfile' + - 'gemfiles/bson_min.gemfile' + - 'gemfiles/driver_master.gemfile' + - 'gemfiles/driver_min.gemfile' + - 'gemfiles/driver_stable.gemfile' + - 'gemfiles/rails_6.1.gemfile' + - 'gemfiles/rails_7.0.gemfile' + - 'gemfiles/rails_7.1.gemfile' + - 'gemfiles/rails_master.gemfile' + - 'spec/integration/associations/foreign_key_spec.rb' + - 'spec/integration/associations/reverse_population_spec.rb' + - 'spec/integration/callbacks_spec.rb' + - 'spec/mongoid/association/auto_save_spec.rb' + - 'spec/mongoid/association/embedded/embedded_in_spec.rb' + - 'spec/mongoid/association/embedded/embeds_many_query_spec.rb' + - 'spec/mongoid/association/embedded/embeds_one_query_spec.rb' + - 'spec/mongoid/association/embedded/embeds_one_spec.rb' + - 'spec/mongoid/association/referenced/belongs_to_query_spec.rb' + - 'spec/mongoid/association/referenced/belongs_to_spec.rb' + - 'spec/mongoid/association/referenced/has_and_belongs_to_many_query_spec.rb' + - 'spec/mongoid/association/referenced/has_and_belongs_to_many_spec.rb' + - 'spec/mongoid/association/referenced/has_many_query_spec.rb' + - 'spec/mongoid/association/referenced/has_many_spec.rb' + - 'spec/mongoid/association/referenced/has_one_query_spec.rb' + - 'spec/mongoid/association/referenced/has_one_spec.rb' + - 'spec/mongoid/attributes/nested_spec.rb' + - 'spec/mongoid/attributes_spec.rb' + - 'spec/mongoid/clients/transactions_spec.rb' + - 'spec/mongoid/copyable_spec.rb' + - 'spec/mongoid/criteria/includable_spec.rb' + - 'spec/mongoid/criteria/queryable/selectable_spec.rb' + - 'spec/mongoid/criteria/queryable/selectable_where_spec.rb' + - 'spec/mongoid/interceptable_spec.rb' + - 'spec/mongoid/shardable_spec.rb' + - 'spec/mongoid/timestamps_spec.rb' + - 'spec/mongoid/touchable_spec.rb' + +# Offense count: 1 +# This cop supports safe autocorrection (--autocorrect). +Style/RedundantParentheses: + Exclude: + - 'lib/mongoid/association/referenced/has_many/enumerable.rb' + +# Offense count: 251 # This cop supports safe autocorrection (--autocorrect). # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns. # URISchemes: http, https diff --git a/docs/reference/crud.txt b/docs/reference/crud.txt index bdbdcbfc5..549ade80b 100644 --- a/docs/reference/crud.txt +++ b/docs/reference/crud.txt @@ -565,7 +565,7 @@ Mongoid models are reverted. For example: person.name # => 'Jake' raise 'An exception' end - rescue Exception + rescue StandardError person.name # => 'Tom' end diff --git a/gemfiles/standard.rb b/gemfiles/standard.rb index e5c4dd392..fed0abd5f 100644 --- a/gemfiles/standard.rb +++ b/gemfiles/standard.rb @@ -8,7 +8,7 @@ def standard_dependencies end group :development, :test do - gem 'rubocop', '~> 1.49.0' + gem 'rubocop', '~> 1.60.0' gem 'rubocop-performance', '~> 1.16.0' gem 'rubocop-rails', '~> 2.17.4' gem 'rubocop-rake', '~> 0.6.0' diff --git a/lib/mongoid/association/embedded/embeds_many.rb b/lib/mongoid/association/embedded/embeds_many.rb index 1aac596f9..d753322ee 100644 --- a/lib/mongoid/association/embedded/embeds_many.rb +++ b/lib/mongoid/association/embedded/embeds_many.rb @@ -49,7 +49,7 @@ def setup! # # @return [ String ] The field name. def store_as - @store_as ||= (@options[:store_as].try(:to_s) || name.to_s) + @store_as ||= @options[:store_as].try(:to_s) || name.to_s end # The key that is used to get the attributes for the associated object. diff --git a/lib/mongoid/association/embedded/embeds_one.rb b/lib/mongoid/association/embedded/embeds_one.rb index d2fe242f2..1032d268b 100644 --- a/lib/mongoid/association/embedded/embeds_one.rb +++ b/lib/mongoid/association/embedded/embeds_one.rb @@ -45,7 +45,7 @@ def setup! # # @return [ String ] The field name. def store_as - @store_as ||= (@options[:store_as].try(:to_s) || name.to_s) + @store_as ||= @options[:store_as].try(:to_s) || name.to_s end # The key that is used to get the attributes for the associated object. diff --git a/lib/mongoid/association/referenced/has_many/buildable.rb b/lib/mongoid/association/referenced/has_many/buildable.rb index bf69c8369..239b5260d 100644 --- a/lib/mongoid/association/referenced/has_many/buildable.rb +++ b/lib/mongoid/association/referenced/has_many/buildable.rb @@ -21,7 +21,7 @@ module Buildable # # @return [ Mongoid::Document ] A single document. def build(base, object, _type = nil, _selected_fields = nil) - return (object || []) unless query?(object) + return object || [] unless query?(object) return [] if object.is_a?(Array) query_criteria(object, base) diff --git a/lib/mongoid/association/relatable.rb b/lib/mongoid/association/relatable.rb index b4ede4984..c408c2770 100644 --- a/lib/mongoid/association/relatable.rb +++ b/lib/mongoid/association/relatable.rb @@ -409,7 +409,7 @@ def validate! raise Errors::InvalidRelationOption.new(@owner_class, name, opt, self.class::VALID_OPTIONS) end - [name, "#{name}?".to_sym, "#{name}=".to_sym].each do |n| + [name, :"#{name}?", :"#{name}="].each do |n| next unless Mongoid.destructive_fields.include?(n) raise Errors::InvalidRelation.new(@owner_class, n) diff --git a/lib/mongoid/clients/sessions.rb b/lib/mongoid/clients/sessions.rb index 202cf63c6..e0edfd54c 100644 --- a/lib/mongoid/clients/sessions.rb +++ b/lib/mongoid/clients/sessions.rb @@ -193,7 +193,7 @@ def abort_transaction(session) # Transforms custom options for after_commit and after_rollback callbacks # into options for +set_callback+. - def set_options_for_callbacks!(args) + def set_options_for_callbacks!(args) # rubocop:disable Naming/AccessorMethodName options = args.extract_options! args << options diff --git a/lib/mongoid/contextual/memory.rb b/lib/mongoid/contextual/memory.rb index 5576c6753..18593f540 100644 --- a/lib/mongoid/contextual/memory.rb +++ b/lib/mongoid/contextual/memory.rb @@ -650,16 +650,16 @@ def apply_sorting # @example Compare the two objects. # context.compare(a, b) # - # @param [ Object ] a The first object. - # @param [ Object ] b The second object. + # @param [ Object ] value_a The first object. + # @param [ Object ] value_b The second object. # # @return [ Integer ] The comparison value. - def compare(a, b) - return 0 if a.nil? && b.nil? - return 1 if a.nil? - return -1 if b.nil? + def compare(value_a, value_b) + return 0 if value_a.nil? && value_b.nil? + return 1 if value_a.nil? + return -1 if value_b.nil? - compare_operand(a) <=> compare_operand(b) + compare_operand(value_a) <=> compare_operand(value_b) end # Sort the documents in place. diff --git a/lib/mongoid/copyable.rb b/lib/mongoid/copyable.rb index 151ab0767..12c4b1a79 100644 --- a/lib/mongoid/copyable.rb +++ b/lib/mongoid/copyable.rb @@ -94,7 +94,7 @@ def process_localized_attributes(klass, attrs) attrs["#{name}_translations"] = value end end - klass.embedded_relations.each do |_, association| + klass.embedded_relations.each_value do |association| next unless attrs.present? && attrs[association.key].present? if association.is_a?(Association::Embedded::EmbedsMany) diff --git a/lib/mongoid/criteria/queryable/extensions/string.rb b/lib/mongoid/criteria/queryable/extensions/string.rb index ee686ad64..9c90e372f 100644 --- a/lib/mongoid/criteria/queryable/extensions/string.rb +++ b/lib/mongoid/criteria/queryable/extensions/string.rb @@ -46,7 +46,7 @@ def __mongo_expression__ # # @return [ Hash ] The string as a sort option hash. def __sort_option__ - split(/,/).inject({}) do |hash, spec| + split(',').inject({}) do |hash, spec| hash.tap do |h| field, direction = spec.strip.split(/\s/) h[field.to_sym] = Mongoid::Criteria::Translator.to_direction(direction) diff --git a/lib/mongoid/criteria/queryable/extensions/symbol.rb b/lib/mongoid/criteria/queryable/extensions/symbol.rb index d4d887957..dd195e3ba 100644 --- a/lib/mongoid/criteria/queryable/extensions/symbol.rb +++ b/lib/mongoid/criteria/queryable/extensions/symbol.rb @@ -34,7 +34,7 @@ module ClassMethods # @param [ String ] additional The additional MongoDB operator. def add_key(name, strategy, operator, additional = nil, &block) define_method(name) do - method = "__#{strategy}__".to_sym + method = :"__#{strategy}__" Key.new(self, method, operator, additional, &block) end end diff --git a/lib/mongoid/criteria/queryable/mergeable.rb b/lib/mongoid/criteria/queryable/mergeable.rb index 44871180d..5d4413a79 100644 --- a/lib/mongoid/criteria/queryable/mergeable.rb +++ b/lib/mongoid/criteria/queryable/mergeable.rb @@ -420,7 +420,7 @@ def prepare(field, operator, value) field = field.to_s name = aliases[field] || field serializer = serializers[name] - value = serializer ? serializer.evolve(value) : value + value = serializer.evolve(value) if serializer end selection = { operator => value } negating? ? { '$not' => selection } : selection diff --git a/lib/mongoid/document.rb b/lib/mongoid/document.rb index 90d55ae8c..31a879448 100644 --- a/lib/mongoid/document.rb +++ b/lib/mongoid/document.rb @@ -409,7 +409,7 @@ def instantiate(attrs = nil, selected_fields = nil, &block) # @api private def instantiate_document(attrs = nil, selected_fields = nil, options = {}, &block) execute_callbacks = options.fetch(:execute_callbacks, Threaded.execute_callbacks?) - attributes = attrs&.to_h || {} + attributes = attrs.to_h doc = allocate doc.__selected_fields = selected_fields diff --git a/lib/mongoid/errors/invalid_field.rb b/lib/mongoid/errors/invalid_field.rb index 0e6584cea..1aa7467d0 100644 --- a/lib/mongoid/errors/invalid_field.rb +++ b/lib/mongoid/errors/invalid_field.rb @@ -57,8 +57,7 @@ def origin(klass, name) # # @return [ Array ] The location of the method. def location(klass, name) - @location ||= - (klass.instance_method(name).source_location || ['Unknown', 0]) + @location ||= klass.instance_method(name).source_location || ['Unknown', 0] end end end diff --git a/lib/mongoid/errors/invalid_relation.rb b/lib/mongoid/errors/invalid_relation.rb index 0f0ee4ddd..bde75057d 100644 --- a/lib/mongoid/errors/invalid_relation.rb +++ b/lib/mongoid/errors/invalid_relation.rb @@ -53,8 +53,7 @@ def origin(klass, name) # # @return [ Array ] The location of the method. def location(klass, name) - @location ||= - (klass.instance_method(name).source_location || ['Unknown', 0]) + @location ||= klass.instance_method(name).source_location || ['Unknown', 0] end end end diff --git a/lib/mongoid/extensions/object.rb b/lib/mongoid/extensions/object.rb index dd3540fc6..91e9c42d6 100644 --- a/lib/mongoid/extensions/object.rb +++ b/lib/mongoid/extensions/object.rb @@ -83,7 +83,6 @@ def __to_inc__ end Mongoid.deprecate(self, :__to_inc__) - # Do or do not, there is no try. -- Yoda. # # @example Do or do not. diff --git a/lib/mongoid/fields/foreign_key.rb b/lib/mongoid/fields/foreign_key.rb index 78b1f9736..9b6f145fc 100644 --- a/lib/mongoid/fields/foreign_key.rb +++ b/lib/mongoid/fields/foreign_key.rb @@ -22,8 +22,8 @@ class ForeignKey < Standard # @param [ Array ] new_elements The new elements to add. # @param [ Array ] old_elements The old elements getting removed. def add_atomic_changes(document, name, key, mods, new_elements, old_elements) - old = (old_elements || []) - new = (new_elements || []) + old = old_elements || [] + new = new_elements || [] if new.length > old.length if new.first(old.length) == old document.atomic_array_add_to_sets[key] = new.drop(old.length) diff --git a/lib/mongoid/fields/standard.rb b/lib/mongoid/fields/standard.rb index 238a4916b..93509ca84 100644 --- a/lib/mongoid/fields/standard.rb +++ b/lib/mongoid/fields/standard.rb @@ -138,8 +138,7 @@ def object_id_field? # # @return [ true | false ] If the field's default is pre-processed. def pre_processed? - @pre_processed ||= - (options[:pre_processed] || (default_val && !default_val.is_a?(::Proc))) + @pre_processed ||= options[:pre_processed] || (default_val && !default_val.is_a?(::Proc)) end # Get the type of this field - inferred from the class name. diff --git a/lib/mongoid/fields/validators/macro.rb b/lib/mongoid/fields/validators/macro.rb index 83f06f43f..e356071da 100644 --- a/lib/mongoid/fields/validators/macro.rb +++ b/lib/mongoid/fields/validators/macro.rb @@ -46,7 +46,7 @@ def validate(klass, name, options) # @param [ Symbol ] name The field name. # @param [ Hash ] _options The provided options. def validate_relation(klass, name, _options = {}) - [name, "#{name}?".to_sym, "#{name}=".to_sym].each do |n| + [name, :"#{name}?", :"#{name}="].each do |n| if Mongoid.destructive_fields.include?(n) raise Errors::InvalidRelation.new(klass, n) end @@ -65,7 +65,7 @@ def validate_relation(klass, name, _options = {}) # # @api private def validate_field_name(klass, name) - [name, "#{name}?".to_sym, "#{name}=".to_sym].each do |n| + [name, :"#{name}?", :"#{name}="].each do |n| if Mongoid.destructive_fields.include?(n) raise Errors::InvalidField.new(klass, name, n) end diff --git a/lib/mongoid/interceptable.rb b/lib/mongoid/interceptable.rb index 85f305ceb..b471ee9eb 100644 --- a/lib/mongoid/interceptable.rb +++ b/lib/mongoid/interceptable.rb @@ -176,7 +176,7 @@ def _mongoid_run_child_callbacks(kind, children: nil, &block) # # @api private def _mongoid_run_child_callbacks_with_around(kind, children: nil, &block) - child, *tail = (children || cascadable_children(kind)) + child, *tail = children || cascadable_children(kind) with_children = !Mongoid::Config.prevent_multiple_calls_of_embedded_callbacks if child.nil? block&.call @@ -199,12 +199,12 @@ def _mongoid_run_child_callbacks_with_around(kind, children: nil, &block) # # @api private def _mongoid_run_child_callbacks_without_around(kind, children: nil, &block) - children = (children || cascadable_children(kind)) + children ||= cascadable_children(kind) callback_list = _mongoid_run_child_before_callbacks(kind, children: children) return false if callback_list == false value = block&.call - callback_list.each do |_next_sequence, env| + callback_list.each_value do |env| env.value &&= value end return false if _mongoid_run_child_after_callbacks(callback_list: callback_list) == false diff --git a/lib/mongoid/matcher/elem_match.rb b/lib/mongoid/matcher/elem_match.rb index 317ec3b1f..ef5e52d9f 100644 --- a/lib/mongoid/matcher/elem_match.rb +++ b/lib/mongoid/matcher/elem_match.rb @@ -33,7 +33,7 @@ def matches?(_exists, value, condition) else # Validate the condition is valid, even though we will never attempt # matching it. - condition.each do |k, _v| + condition.each_key do |k| k = k.to_s next unless k.start_with?('$') diff --git a/lib/mongoid/railties/database.rake b/lib/mongoid/railties/database.rake index 8a6d6ae99..d49ce8cc5 100644 --- a/lib/mongoid/railties/database.rake +++ b/lib/mongoid/railties/database.rake @@ -84,9 +84,9 @@ namespace :db do task remove_indexes: :'mongoid:remove_indexes' end - unless Rake::Task.task_defined?('db:remove_indexes') - desc 'Remove indexes specified in Mongoid models' - task remove_indexes: 'mongoid:remove_indexes' + unless Rake::Task.task_defined?('db:remove_search_indexes') + desc 'Remove search indexes specified in Mongoid models' + task remove_search_indexes: 'mongoid:remove_search_indexes' end unless Rake::Task.task_defined?('db:shard_collections') diff --git a/lib/mongoid/tasks/database.rb b/lib/mongoid/tasks/database.rb index 7f272d361..fff8805a5 100644 --- a/lib/mongoid/tasks/database.rb +++ b/lib/mongoid/tasks/database.rb @@ -25,7 +25,7 @@ def create_collections(models = ::Mongoid.models, force: false) else logger.info("MONGOID: collection options ignored on: #{model}, please define in the root model.") end - rescue Exception + rescue StandardError logger.error "error while creating collection for #{model}" raise end @@ -250,10 +250,9 @@ def wait_for_search_indexes(models) models.each do |model, names| model.wait_for_search_indexes(names) do |status| if status.ready? - puts logger.info("MONGOID: Search indexes on #{model} are READY") else - print '.' + print '.' # rubocop:disable Rails/Output $stdout.flush end end diff --git a/lib/mongoid/warnings.rb b/lib/mongoid/warnings.rb index ddd357739..67cee0cc6 100644 --- a/lib/mongoid/warnings.rb +++ b/lib/mongoid/warnings.rb @@ -19,10 +19,10 @@ class << self def warning(id, message) singleton_class.class_eval do define_method("warn_#{id}") do - unless instance_variable_get("@#{id}") - Mongoid.logger.warn(message) - instance_variable_set("@#{id}", true) - end + return if instance_variable_get("@#{id}") + + Mongoid.logger.warn(message) + instance_variable_set("@#{id}", true) end end end diff --git a/mongoid.gemspec b/mongoid.gemspec index 437483e93..cf9a0cf10 100644 --- a/mongoid.gemspec +++ b/mongoid.gemspec @@ -26,8 +26,6 @@ Gem::Specification.new do |s| } s.required_ruby_version = '>= 2.7' - - s.required_ruby_version = '>= 2.7' s.required_rubygems_version = '>= 1.3.6' # activemodel 7.0.0 cannot be used due to Class#descendants issue diff --git a/spec/integration/callbacks_spec.rb b/spec/integration/callbacks_spec.rb index c24cb0a1f..665b17401 100644 --- a/spec/integration/callbacks_spec.rb +++ b/spec/integration/callbacks_spec.rb @@ -584,7 +584,7 @@ def will_save_change_to_attribute_values_before end context 'cascade callbacks' do - ruby_version_gte '3.0' + min_ruby_version '3.0' require_mri let(:book) do diff --git a/spec/mongoid/config/environment_spec.rb b/spec/mongoid/config/environment_spec.rb index f4b03d93e..8ccbceba0 100644 --- a/spec/mongoid/config/environment_spec.rb +++ b/spec/mongoid/config/environment_spec.rb @@ -152,7 +152,7 @@ hosts: [localhost] options: auto_encryption_options: - schema_map: #{schema_map.to_yaml.delete_prefix('---').gsub(/\n/, "\n#{' ' * 100}")} + schema_map: #{schema_map.to_yaml.delete_prefix('---').gsub("\n", "\n#{' ' * 100}")} FILE end diff --git a/spec/mongoid/contextual/mongo_spec.rb b/spec/mongoid/contextual/mongo_spec.rb index 2e037c4d3..ed5447aae 100644 --- a/spec/mongoid/contextual/mongo_spec.rb +++ b/spec/mongoid/contextual/mongo_spec.rb @@ -3693,22 +3693,21 @@ expect(new_order.reload.name).to eq('Smiths') end end - end context 'when operation is $push' do before do depeche_mode.update_attribute(:genres, ['electronic']) new_order.update_attribute(:genres, ['electronic']) - context.update_all("$push" => { genres: 'pop' }) + context.update_all('$push' => { genres: 'pop' }) end it 'updates the first matching document' do - expect(depeche_mode.reload.genres).to eq(['electronic', 'pop']) + expect(depeche_mode.reload.genres).to eq(%w[electronic pop]) end it 'updates the last matching document' do - expect(new_order.reload.genres).to eq(['electronic', 'pop']) + expect(new_order.reload.genres).to eq(%w[electronic pop]) end end diff --git a/spec/mongoid/criteria/findable_spec.rb b/spec/mongoid/criteria/findable_spec.rb index 16435ca42..527e75e41 100644 --- a/spec/mongoid/criteria/findable_spec.rb +++ b/spec/mongoid/criteria/findable_spec.rb @@ -390,7 +390,6 @@ expect(found).to include(band_two) end - context 'when any id does not match' do context 'when raising a not found error' do diff --git a/spec/mongoid/document_persistence_context_spec.rb b/spec/mongoid/document_persistence_context_spec.rb index f8633a7ce..baf2e2fe6 100644 --- a/spec/mongoid/document_persistence_context_spec.rb +++ b/spec/mongoid/document_persistence_context_spec.rb @@ -96,7 +96,7 @@ end it 'cannot be reloaded without specifying the context' do - expect { person.reload }.to raise_error + expect { person.reload }.to raise_error(Mongoid::Errors::DocumentNotFound, /Document\(s\) not found for class Person with id\(s\)/) end it 'cannot be updated without specifying the context' do diff --git a/spec/mongoid/fields/foreign_key_spec.rb b/spec/mongoid/fields/foreign_key_spec.rb index 1f416fcd3..e5a269b6c 100644 --- a/spec/mongoid/fields/foreign_key_spec.rb +++ b/spec/mongoid/fields/foreign_key_spec.rb @@ -511,7 +511,7 @@ end let(:association) { Game.relations['person'] } - context 'type is Array' do + context 'when type is Array' do let(:type) { Array } context 'when the object is a BSON::ObjectId' do @@ -687,7 +687,7 @@ end end - context 'type is Set' do + context 'when type is Set' do let(:type) { Set } context 'when the object is an Array of BSON::ObjectId' do @@ -707,7 +707,7 @@ end end - context 'type is Object' do + context 'when type is Object' do let(:type) { Object } context 'when the object is a BSON::ObjectId' do @@ -743,7 +743,7 @@ end context 'when the object is nil' do - let(:object) { '' } + let(:object) { nil } it 'returns nil' do expect(mongoized).to be_nil diff --git a/spec/mongoid/interceptable_spec.rb b/spec/mongoid/interceptable_spec.rb index 86d32b6f3..1453ffb42 100644 --- a/spec/mongoid/interceptable_spec.rb +++ b/spec/mongoid/interceptable_spec.rb @@ -2575,12 +2575,10 @@ class TestClass end end - before do + it 'logs a warning' do expect(Mongoid.logger).to receive(:warn).with(/Around callbacks are disabled for embedded documents/).twice.and_call_original expect(Mongoid.logger).to receive(:warn).with(/To enable around callbacks for embedded documents/).twice.and_call_original - end - it 'logs a warning' do parent.save! end end diff --git a/spec/mongoid/interceptable_spec_models.rb b/spec/mongoid/interceptable_spec_models.rb index fa4c41442..7bad8f01b 100644 --- a/spec/mongoid/interceptable_spec_models.rb +++ b/spec/mongoid/interceptable_spec_models.rb @@ -20,18 +20,18 @@ module CallbackTracking whens = %i[before after] %i[validation save create update].each do |what| whens.each do |whn| - send("#{whn}_#{what}", "#{whn}_#{what}_stub".to_sym) + send("#{whn}_#{what}", :"#{whn}_#{what}_stub") define_method("#{whn}_#{what}_stub") do - callback_registry&.record_call(self.class, "#{whn}_#{what}".to_sym) + callback_registry&.record_call(self.class, :"#{whn}_#{what}") end end next if what == :validation - send("around_#{what}", "around_#{what}_stub".to_sym) + send("around_#{what}", :"around_#{what}_stub") define_method("around_#{what}_stub") do |&block| - callback_registry&.record_call(self.class, "around_#{what}_open".to_sym) + callback_registry&.record_call(self.class, :"around_#{what}_open") block.call - callback_registry&.record_call(self.class, "around_#{what}_close".to_sym) + callback_registry&.record_call(self.class, :"around_#{what}_close") end end end diff --git a/spec/mongoid/tasks/database_spec.rb b/spec/mongoid/tasks/database_spec.rb index e402ae8c3..bcfeb3678 100644 --- a/spec/mongoid/tasks/database_spec.rb +++ b/spec/mongoid/tasks/database_spec.rb @@ -224,44 +224,32 @@ class Note end context 'when wait is true' do - before do - allow(described_class).to receive(:wait_for_search_indexes) - described_class.create_search_indexes([searchable_model_spy], wait: true) - end - it 'invokes both create_search_indexes and wait_for_search_indexes' do - expect(searchable_model_spy).to have_received(:create_search_indexes) - expect(described_class).to have_received(:wait_for_search_indexes).with(searchable_model_spy => index_names) + expect(searchable_model_spy).to receive(:create_search_indexes) + expect(described_class).to receive(:wait_for_search_indexes).with(searchable_model_spy => index_names) + + described_class.create_search_indexes([searchable_model_spy], wait: true) end end context 'when wait is false' do - before do - allow(described_class).to receive(:wait_for_search_indexes) - described_class.create_search_indexes([searchable_model_spy], wait: false) - end - it 'invokes only create_search_indexes' do - expect(searchable_model_spy).to have_received(:create_search_indexes) - expect(described_class).to_not have_received(:wait_for_search_indexes) + expect(searchable_model_spy).to receive(:create_search_indexes) + expect(described_class).to_not receive(:wait_for_search_indexes) + + described_class.create_search_indexes([searchable_model_spy], wait: false) end end end describe '.remove_search_indexes' do - before do + it 'calls remove_search_indexes on all non-embedded models' do models.each do |model| - allow(model).to receive(:remove_search_indexes) unless model.embedded? + expect(model).to receive(:remove_search_indexes) unless model.embedded? end described_class.remove_search_indexes(models) end - - it 'calls remove_search_indexes on all non-embedded models' do - models.each do |model| - expect(model).to have_received(:remove_search_indexes) unless model.embedded? - end - end end describe '.undefined_indexes' do diff --git a/spec/mongoid/validatable/uniqueness_spec.rb b/spec/mongoid/validatable/uniqueness_spec.rb index b6eff724e..5b7d9582a 100644 --- a/spec/mongoid/validatable/uniqueness_spec.rb +++ b/spec/mongoid/validatable/uniqueness_spec.rb @@ -2486,7 +2486,7 @@ class SpanishActor < EuropeanActor it 'is invalid' do subclass_document_with_duplicated_name.tap do |d| - expect(d).to be_invalid + expect(d).to_not be_valid expect(d.errors[:name]).to eq(['has already been taken']) end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 957d2e833..9314992f4 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -112,8 +112,6 @@ class Query inflect.singular('address_components', 'address_component') end -Time.zone = 'UTC' - I18n.config.enforce_available_locales = false if %w[yes true 1].include?((ENV['TEST_I18N_FALLBACKS'] || '').downcase) diff --git a/spec/support/constraints.rb b/spec/support/constraints.rb index c570549e1..0bd670643 100644 --- a/spec/support/constraints.rb +++ b/spec/support/constraints.rb @@ -50,6 +50,16 @@ def without_i18n_fallbacks end end + def local_env(env = nil) + around do |example| + saved_env = ENV.to_h + ENV.update(env || yield) + example.run + ensure + ENV.replace(saved_env) + end + end + def require_mri before(:all) do unless SpecConfig.instance.mri?