Class: RuboCop::Cop::Rails::DynamicFindBy

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
ActiveRecordHelper
Defined in:
lib/rubocop/cop/rails/dynamic_find_by.rb

Overview

Checks dynamic ‘find_by_*` methods. Use `find_by` instead of dynamic method. See. rails.rubystyle.guide#find_by

Examples:

# bad
User.find_by_name(name)
User.find_by_name_and_email(name)
User.find_by_email!(name)

# good
User.find_by(name: name)
User.find_by(name: name, email: email)
User.find_by!(email: email)

AllowedMethods: [‘find_by_sql’, ‘find_by_token_for’] (default)

# bad
User.find_by_query(users_query)
User.find_by_token_for(:password_reset, token)

# good
User.find_by_sql(users_sql)
User.find_by_token_for(:password_reset, token)

AllowedReceivers: [‘Gem::Specification’, ‘page’] (default)

# bad
Specification.find_by_name('backend').gem_dir
page.find_by_id('a_dom_id').click

# good
Gem::Specification.find_by_name('backend').gem_dir
page.find_by_id('a_dom_id').click

Constant Summary collapse

MSG =
'Use `%<static_name>s` instead of dynamic `%<method>s`.'
METHOD_PATTERN =
/^find_by_(.+?)(!)?$/.freeze
IGNORED_ARGUMENT_TYPES =
%i[hash splat].freeze

Constants included from ActiveRecordHelper

ActiveRecordHelper::WHERE_METHODS

Instance Method Summary collapse

Methods included from ActiveRecordHelper

#external_dependency_checksum, #foreign_key_of, #in_where?, #inherit_active_record_base?, #polymorphic?, #resolve_relation_into_column, #schema, #table_name

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/rails/dynamic_find_by.rb', line 50

def on_send(node)
  return if (node.receiver.nil? && !inherit_active_record_base?(node)) || allowed_invocation?(node)

  method_name = node.method_name
  static_name = static_method_name(method_name)
  return unless static_name
  return unless dynamic_find_by_arguments?(node)

  message = format(MSG, static_name: static_name, method: method_name)
  add_offense(node, message: message) do |corrector|
    autocorrect(corrector, node)
  end
end