class Gitlab::Styles::Rubocop::Cop::CodeReuse::ActiveRecord
Cop
that denies the use of ActiveRecord
methods outside of models.
Constants
- MSG
- NOT_ALLOWED
Various methods from ActiveRecord::Querying that are denied. We exclude some generic ones such as `any?` and `first`, as these may lead to too many false positives, since `Array` also supports these methods.
The keys of this Hash are the denied method names. The values are booleans that indicate if the method should only be denied if any arguments are provided.
Public Instance Methods
# File lib/gitlab/styles/rubocop/cop/code_reuse/active_record.rb, line 122 def allowed_scopes @allowed_scopes ||= Set.new end
We can not auto correct code like this, as it requires manual refactoring. Instead, we'll just allow the surrounding scope.
Despite this method's presence, you should not use it. This method exists to make it possible to allow large chunks of offenses we can't fix in the short term. If you are writing new code, follow the code reuse guidelines, instead of allowing any new offenses.
# File lib/gitlab/styles/rubocop/cop/code_reuse/active_record.rb, line 87 def autocorrect(node) scope = surrounding_scope_of(node) indent = indentation_of(scope) lambda do |corrector| # This prevents us from inserting the same enable/disable comment # for a method or block that has multiple offenses. next if allowed_scopes.include?(scope) corrector.insert_before( scope.source_range, "# rubocop: disable #{cop_name}\n#{indent}" ) corrector.insert_after( scope.source_range, "\n#{indent}# rubocop: enable #{cop_name}" ) allowed_scopes << scope end end
# File lib/gitlab/styles/rubocop/cop/code_reuse/active_record.rb, line 110 def indentation_of(node) ' ' * node.loc.expression.source_line[/\A */].length end
# File lib/gitlab/styles/rubocop/cop/code_reuse/active_record.rb, line 64 def on_send(node) receiver = node.children[0] send_name = node.children[1] first_arg = node.children[2] return unless receiver && NOT_ALLOWED.key?(send_name) # If the rule requires an argument to be given, but none are # provided, we won't register an offense. This prevents us from # adding offenses for `project.group`, while still covering # `Project.group(:name)`. return if NOT_ALLOWED[send_name] && !first_arg add_offense(node, location: :selector) end
# File lib/gitlab/styles/rubocop/cop/code_reuse/active_record.rb, line 114 def surrounding_scope_of(node) %i[def defs block begin].each do |type| if (found = node.each_ancestor(type).first) return found end end end