diff options
-rw-r--r-- | .rubocop.yml | 3 | ||||
-rw-r--r-- | rubocop/cop/gitlab/models_inherit_application_record.rb | 41 | ||||
-rw-r--r-- | rubocop/model_helpers.rb | 10 | ||||
-rw-r--r-- | rubocop/rubocop.rb | 1 |
4 files changed, 55 insertions, 0 deletions
diff --git a/.rubocop.yml b/.rubocop.yml index a95ded8af1c..ffa77799a91 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -163,6 +163,9 @@ Gitlab/ModuleWithInstanceVariables: Gitlab/HTTParty: Enabled: true +Gitlab/ModelsInheritApplicationRecord: + Enabled: true + GitlabSecurity/PublicSend: Enabled: true Exclude: diff --git a/rubocop/cop/gitlab/models_inherit_application_record.rb b/rubocop/cop/gitlab/models_inherit_application_record.rb new file mode 100644 index 00000000000..1172930d1a2 --- /dev/null +++ b/rubocop/cop/gitlab/models_inherit_application_record.rb @@ -0,0 +1,41 @@ +require_relative '../../model_helpers' + +module RuboCop + module Cop + module Models + # This cop checks for models that extend from ActiveRecord::Base + # + # @example + # # bad + # class MyModel < ActiveRecord::Base + # + # # good + # class MyModel < ApplicationRecord + class ModelsInheritApplicationRecord < RuboCop::Cop::Cop + include ModelHelpers + + MESSAGE = <<~EOL.freeze + Models should not inherit from ActiveRecord::Base anymore. Please inherit ApplicationRecord instead + + Rails 5 upgrade item 5.2 dictates all Models inherit from ApplicationRecord + + https://edgeguides.rubyonrails.org/upgrading_ruby_on_rails.html#active-record-models-now-inherit-from-applicationrecord-by-default + EOL + + + def_node_matcher :extends_activerecord_base?, <<~PATTERN + (class + (const nil ...) + (const + (const nil :ActiveRecord) :Base) nil) + PATTERN + + def on_send(node) + return unless model?(node) + + add_offense(node, location: :expression, message: MESSAGE) if extends_activerecord_base?(node) + end + end + end + end +end diff --git a/rubocop/model_helpers.rb b/rubocop/model_helpers.rb new file mode 100644 index 00000000000..177dc5cd923 --- /dev/null +++ b/rubocop/model_helpers.rb @@ -0,0 +1,10 @@ +module RuboCop + # Module containing helper methods for writing Model cops. + module ModelHelpers + def model?(node) + path = node.location.expression.source_buffer.name + + path.start_with?(File.join(Dir.pwd, 'models')) + end + end +end diff --git a/rubocop/rubocop.rb b/rubocop/rubocop.rb index 6c9b8753c1a..bad746234ff 100644 --- a/rubocop/rubocop.rb +++ b/rubocop/rubocop.rb @@ -2,6 +2,7 @@ require_relative 'cop/gitlab/module_with_instance_variables' require_relative 'cop/gitlab/predicate_memoization' require_relative 'cop/gitlab/httparty' +require_relative 'cop/gitlab/models_inherit_application_record' require_relative 'cop/gitlab/finder_with_find_by' require_relative 'cop/gitlab/union' require_relative 'cop/include_sidekiq_worker' |