Merge pull request #13837 from Homebrew/dependabot/bundler/Library/Homebrew/rubocop-rails-2.16.0

build(deps): bump rubocop-rails from 2.15.2 to 2.16.0 in /Library/Homebrew
This commit is contained in:
Mike McQuaid 2022-09-09 19:32:18 +01:00 committed by GitHub
commit 2d0c32fa91
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
140 changed files with 1036 additions and 344 deletions

View File

@ -139,10 +139,10 @@ GEM
rubocop-performance (1.14.3)
rubocop (>= 1.7.0, < 2.0)
rubocop-ast (>= 0.4.0)
rubocop-rails (2.15.2)
rubocop-rails (2.16.0)
activesupport (>= 4.2.0)
rack (>= 1.1)
rubocop (>= 1.7.0, < 2.0)
rubocop (>= 1.33.0, < 2.0)
rubocop-rspec (2.12.1)
rubocop (~> 1.31)
rubocop-sorbet (0.6.11)

View File

@ -53,6 +53,7 @@ module RuboCop::Cop::EnforceSuperclass
end
end
RuboCop::Cop::IgnoredMethods = RuboCop::Cop::AllowedMethods
RuboCop::Cop::IgnoredPattern = RuboCop::Cop::AllowedPattern
module RuboCop::Cop::IndexMethod
@ -125,6 +126,25 @@ end
module RuboCop::Cop::Rails; end
class RuboCop::Cop::Rails::ActionControllerFlashBeforeRender < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
def action_controller?(param0); end
def flash_assignment?(param0); end
def on_send(flash_node); end
def render?(param0); end
private
def find_ancestor(node, type:); end
def followed_by_render?(flash_node); end
def inherit_action_controller_base?(node); end
def instance_method_or_block?(node); end
end
RuboCop::Cop::Rails::ActionControllerFlashBeforeRender::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::ActionControllerFlashBeforeRender::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::ActionControllerTestCase < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
extend ::RuboCop::Cop::TargetRailsVersion
@ -217,6 +237,16 @@ RuboCop::Cop::Rails::ActiveSupportAliases::ALIASES = T.let(T.unsafe(nil), Hash)
RuboCop::Cop::Rails::ActiveSupportAliases::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::ActiveSupportAliases::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::ActiveSupportOnLoad < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
def on_send(node); end
end
RuboCop::Cop::Rails::ActiveSupportOnLoad::LOAD_HOOKS = T.let(T.unsafe(nil), Hash)
RuboCop::Cop::Rails::ActiveSupportOnLoad::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::ActiveSupportOnLoad::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::AddColumnIndex < ::RuboCop::Cop::Base
include ::RuboCop::Cop::RangeHelp
extend ::RuboCop::Cop::AutoCorrector
@ -545,7 +575,7 @@ class RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods < ::RuboCop::Cop::
extend ::RuboCop::Cop::AutoCorrector
def any_manipulation?(param0 = T.unsafe(nil)); end
def errors_keys?(param0 = T.unsafe(nil)); end
def errors_deprecated?(param0 = T.unsafe(nil)); end
def messages_details_assignment?(param0 = T.unsafe(nil)); end
def messages_details_manipulation?(param0 = T.unsafe(nil)); end
def on_send(node); end
@ -561,9 +591,11 @@ class RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods < ::RuboCop::Cop::
def offense_range(node, receiver); end
def receiver_matcher(node); end
def replacement(node, receiver); end
def skip_autocorrect?(node); end
end
RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods::AUTOCORECTABLE_METHODS = T.let(T.unsafe(nil), Array)
RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods::AUTOCORRECTABLE_METHODS = T.let(T.unsafe(nil), Array)
RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods::INCOMPATIBLE_METHODS = T.let(T.unsafe(nil), Array)
RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods::MANIPULATIVE_METHODS = T.let(T.unsafe(nil), Set)
RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods::MSG = T.let(T.unsafe(nil), String)
@ -837,6 +869,8 @@ RuboCop::Cop::Rails::FindById::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::FindEach < ::RuboCop::Cop::Base
include ::RuboCop::Cop::ActiveRecordHelper
include ::RuboCop::Cop::AllowedMethods
include ::RuboCop::Cop::AllowedPattern
extend ::RuboCop::Cop::AutoCorrector
def on_send(node); end
@ -852,6 +886,24 @@ RuboCop::Cop::Rails::FindEach::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::FindEach::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
RuboCop::Cop::Rails::FindEach::SCOPE_METHODS = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::FreezeTime < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
def on_send(node); end
def time_now?(param0 = T.unsafe(nil)); end
def zoned_time_now?(param0 = T.unsafe(nil)); end
private
def current_time?(node, method_name); end
def current_time_with_convert?(node, method_name); end
end
RuboCop::Cop::Rails::FreezeTime::CONV_METHODS = T.let(T.unsafe(nil), Array)
RuboCop::Cop::Rails::FreezeTime::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::FreezeTime::NOW_METHODS = T.let(T.unsafe(nil), Array)
RuboCop::Cop::Rails::FreezeTime::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::HasAndBelongsToMany < ::RuboCop::Cop::Base
def on_send(node); end
end
@ -1486,12 +1538,13 @@ class RuboCop::Cop::Rails::RedundantReceiverInWithOptions < ::RuboCop::Cop::Base
def all_block_nodes_in(param0); end
def all_send_nodes_in(param0); end
def on_block(node); end
def with_options?(param0 = T.unsafe(nil)); end
def on_numblock(node); end
private
def autocorrect(corrector, node); end
def autocorrect(corrector, send_node, node); end
def block_argument_range(node); end
def redundant_receiver?(send_nodes, node); end
def same_value?(arg_node, recv_node); end
def search_begin_pos_of_space_before_block_argument(begin_pos); end
end
@ -1517,6 +1570,7 @@ class RuboCop::Cop::Rails::ReflectionClassName < ::RuboCop::Cop::Base
private
def reflection_class_value?(class_value); end
def str_assigned?(reflection_class_name); end
end
RuboCop::Cop::Rails::ReflectionClassName::ALLOWED_REFLECTION_CLASS_TYPES = T.let(T.unsafe(nil), Array)
@ -1621,6 +1675,7 @@ class RuboCop::Cop::Rails::ReversibleMigration < ::RuboCop::Cop::Base
def drop_table_call(param0 = T.unsafe(nil)); end
def irreversible_schema_statement_call(param0 = T.unsafe(nil)); end
def on_block(node); end
def on_numblock(node); end
def on_send(node); end
def remove_column_call(param0 = T.unsafe(nil)); end
def remove_columns_call(param0 = T.unsafe(nil)); end
@ -1672,6 +1727,26 @@ end
RuboCop::Cop::Rails::RootJoinChain::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::RootJoinChain::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Set)
class RuboCop::Cop::Rails::RootPathnameMethods < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
def on_send(node); end
def pathname_method(param0 = T.unsafe(nil)); end
def rails_root?(param0 = T.unsafe(nil)); end
def rails_root_pathname?(param0 = T.unsafe(nil)); end
private
def evidence(node); end
end
RuboCop::Cop::Rails::RootPathnameMethods::DIR_METHODS = T.let(T.unsafe(nil), Set)
RuboCop::Cop::Rails::RootPathnameMethods::FILE_METHODS = T.let(T.unsafe(nil), Set)
RuboCop::Cop::Rails::RootPathnameMethods::FILE_TEST_METHODS = T.let(T.unsafe(nil), Set)
RuboCop::Cop::Rails::RootPathnameMethods::FILE_UTILS_METHODS = T.let(T.unsafe(nil), Set)
RuboCop::Cop::Rails::RootPathnameMethods::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::RootPathnameMethods::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Set)
class RuboCop::Cop::Rails::RootPublicPath < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
@ -1925,6 +2000,31 @@ end
RuboCop::Cop::Rails::ToFormattedS::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::ToFormattedS::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::ToSWithArgument < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
extend ::RuboCop::Cop::TargetRailsVersion
def on_csend(node); end
def on_send(node); end
end
RuboCop::Cop::Rails::ToSWithArgument::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::ToSWithArgument::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::TopLevelHashWithIndifferentAccess < ::RuboCop::Cop::Base
extend ::RuboCop::Cop::AutoCorrector
extend ::RuboCop::Cop::TargetRailsVersion
def on_const(node); end
def top_level_hash_with_indifferent_access?(param0 = T.unsafe(nil)); end
private
def autocorrect(corrector, node); end
end
RuboCop::Cop::Rails::TopLevelHashWithIndifferentAccess::MSG = T.let(T.unsafe(nil), String)
class RuboCop::Cop::Rails::TransactionExitStatement < ::RuboCop::Cop::Base
def exit_statements(param0); end
def on_send(node); end
@ -2084,6 +2184,31 @@ end
RuboCop::Cop::Rails::WhereExists::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::WhereExists::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::WhereMissing < ::RuboCop::Cop::Base
include ::RuboCop::Cop::RangeHelp
extend ::RuboCop::Cop::AutoCorrector
extend ::RuboCop::Cop::TargetRailsVersion
def missing_relationship(param0); end
def on_send(node); end
def where_node_and_argument(param0); end
private
def message(node, where_argument); end
def multi_condition?(where_arg); end
def register_offense(node, where_node, where_argument, range); end
def remove_where_method(corrector, node, where_node); end
def replace_range(child); end
def replace_where_method(corrector, where_node); end
def root_receiver(node); end
def same_line?(left_joins_node, where_node); end
def same_relationship?(where, left_joins); end
end
RuboCop::Cop::Rails::WhereMissing::MSG = T.let(T.unsafe(nil), String)
RuboCop::Cop::Rails::WhereMissing::RESTRICT_ON_SEND = T.let(T.unsafe(nil), Array)
class RuboCop::Cop::Rails::WhereNot < ::RuboCop::Cop::Base
include ::RuboCop::Cop::RangeHelp
extend ::RuboCop::Cop::AutoCorrector

View File

@ -4926,9 +4926,11 @@ module RuboCop::AST::NodePattern::Sets
SET_BUILD_RECOMMENDED_TEST_OPTIONAL = ::T.let(nil, ::T.untyped)
SET_DEPENDS_ON_USES_FROM_MACOS = ::T.let(nil, ::T.untyped)
SET_INCLUDE_WITH_WITHOUT = ::T.let(nil, ::T.untyped)
SET_KEYS_VALUES_TO_H_TO_XML = ::T.let(nil, ::T.untyped)
SET_ON_INTEL_ON_ARM = ::T.let(nil, ::T.untyped)
SET_OR_NEWER_OR_OLDER = ::T.let(nil, ::T.untyped)
SET_SYSTEM_SHELL_OUTPUT_PIPE_OUTPUT = ::T.let(nil, ::T.untyped)
SET_TIME_DATETIME = ::T.let(nil, ::T.untyped)
SET_WITH_WITHOUT = ::T.let(nil, ::T.untyped)
SET____ETC_4 = ::T.let(nil, ::T.untyped)
end

View File

@ -88,7 +88,7 @@ $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-progressbar-1.11
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unicode-display_width-2.2.0/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-1.35.1/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-performance-1.14.3/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rails-2.15.2/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rails-2.16.0/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rspec-2.12.1/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-sorbet-0.6.11/lib"
$:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-macho-3.0.0/lib"

View File

@ -1,7 +0,0 @@
#
# Configuration for obsoletion.
#
# See: https://docs.rubocop.org/rubocop/extensions.html#config-obsoletions
#
extracted:
Rails/*: ~

View File

@ -10,6 +10,9 @@ AllCops:
# Exclude db/schema.rb and db/[CONFIGURATION_NAMESPACE]_schema.rb by default.
# See: https://guides.rubyonrails.org/active_record_multiple_databases.html#setting-up-your-application
- db/*schema.rb
# Enable checking Active Support extensions.
# See: https://docs.rubocop.org/rubocop/configuration.html#enable-checking-active-support-extensions
ActiveSupportExtensionsEnabled: true
# What version of Rails is the inspected code using? If a value is specified
# for TargetRailsVersion then it is used. Acceptable values are specified
# as a float (i.e. 5.1); the patch version of Rails should not be included.
@ -23,6 +26,24 @@ Lint/NumberConversion:
# Add Rails' duration methods to the ignore list for `Lint/NumberConversion`
# so that calling `to_i` on one of these does not register an offense.
# See: https://github.com/rubocop/rubocop/issues/8950
AllowedMethods:
- ago
- from_now
- second
- seconds
- minute
- minutes
- hour
- hours
- day
- days
- week
- weeks
- fortnight
- fortnights
- in_milliseconds
AllowedPatterns: []
# Deprecated.
IgnoredMethods:
- ago
- from_now
@ -40,6 +61,18 @@ Lint/NumberConversion:
- fortnights
- in_milliseconds
Rails:
Enabled: true
DocumentationBaseURL: https://docs.rubocop.org/rubocop-rails
Rails/ActionControllerFlashBeforeRender:
Description: 'Use `flash.now` instead of `flash` before `render`.'
StyleGuide: 'https://rails.rubystyle.guide/#flash-before-render'
Reference: 'https://api.rubyonrails.org/classes/ActionController/FlashBeforeRender.html'
Enabled: 'pending'
SafeAutocorrect: false
VersionAdded: '2.16'
Rails/ActionControllerTestCase:
Description: 'Use `ActionDispatch::IntegrationTest` instead of `ActionController::TestCase`.'
StyleGuide: 'https://rails.rubystyle.guide/#integration-testing'
@ -96,6 +129,15 @@ Rails/ActiveSupportAliases:
Enabled: true
VersionAdded: '0.48'
Rails/ActiveSupportOnLoad:
Description: 'Use `ActiveSupport.on_load(...)` to patch Rails framework classes.'
Enabled: 'pending'
Reference:
- 'https://api.rubyonrails.org/classes/ActiveSupport/LazyLoadHooks.html'
- 'https://guides.rubyonrails.org/engines.html#available-load-hooks'
SafeAutoCorrect: false
VersionAdded: '2.16'
Rails/AddColumnIndex:
Description: >-
Rails migrations don't make use of a given `index` key, but also
@ -407,6 +449,14 @@ Rails/FindEach:
VersionChanged: '2.9'
Include:
- app/models/**/*.rb
AllowedMethods:
# Methods that don't work well with `find_each`.
- order
- limit
- select
- lock
AllowedPatterns: []
# Deprecated.
IgnoredMethods:
# Methods that don't work well with `find_each`.
- order
@ -414,6 +464,13 @@ Rails/FindEach:
- select
- lock
Rails/FreezeTime:
Description: 'Prefer `freeze_time` over `travel_to` with an argument of the current time.'
StyleGuide: 'https://rails.rubystyle.guide/#freeze-time'
Enabled: pending
VersionAdded: '2.16'
SafeAutoCorrect: false
Rails/HasAndBelongsToMany:
Description: 'Prefer has_many :through to has_and_belongs_to_many.'
StyleGuide: 'https://rails.rubystyle.guide#has-many-through'
@ -785,6 +842,11 @@ Rails/RootJoinChain:
Enabled: pending
VersionAdded: '2.13'
Rails/RootPathnameMethods:
Description: 'Use `Rails.root` IO methods instead of passing it to `File`.'
Enabled: pending
VersionAdded: '2.16'
Rails/RootPublicPath:
Description: "Favor `Rails.public_path` over `Rails.root` with `'public'`."
Enabled: pending
@ -937,6 +999,18 @@ Rails/ToFormattedS:
- to_formatted_s
VersionAdded: '2.15'
Rails/ToSWithArgument:
Description: 'Identifies passing any argument to `#to_s`.'
Enabled: pending
Safe: false
VersionAdded: '2.16'
Rails/TopLevelHashWithIndifferentAccess:
Description: 'Identifies top-level `HashWithIndifferentAccess`.'
Reference: 'https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#top-level-hashwithindifferentaccess-is-soft-deprecated'
Enabled: pending
VersionAdded: '2.16'
Rails/TransactionExitStatement:
Description: 'Avoid the usage of `return`, `break` and `throw` in transaction blocks.'
Enabled: pending
@ -1003,6 +1077,12 @@ Rails/WhereExists:
VersionAdded: '2.7'
VersionChanged: '2.10'
Rails/WhereMissing:
Description: 'Use `where.missing(...)` to find missing relationship records.'
StyleGuide: 'https://rails.rubystyle.guide/#finding-missing-relationship-records'
Enabled: pending
VersionAdded: '2.16'
Rails/WhereNot:
Description: 'Use `where.not(...)` instead of manually constructing negated SQL in `where`.'
StyleGuide: 'https://rails.rubystyle.guide/#hash-conditions'

View File

@ -0,0 +1,17 @@
#
# Configuration for obsoletion.
#
# See: https://docs.rubocop.org/rubocop/extensions.html#config-obsoletions
#
extracted:
Rails/*: ~
# Cop parameters that have been changed
# Can be treated as a warning instead of a failure with `severity: warning`
changed_parameters:
- cops: Rails/FindEach
parameters: IgnoredMethods
alternatives:
- AllowedMethods
- AllowedPatterns
severity: warning

View File

@ -48,10 +48,7 @@ module RuboCop
class_nodes = class_node.defined_module.each_node
namespaces = class_node.each_ancestor(:class, :module).map(&:identifier)
[*class_nodes, *namespaces]
.reverse
.map { |node| node.children[1] }.join('_')
.tableize
[*class_nodes, *namespaces].reverse.map { |node| node.children[1] }.join('_').tableize
end
# Resolve relation into column name.

View File

@ -10,9 +10,7 @@ module RuboCop
bigint binary boolean date datetime decimal float integer json string
text time timestamp virtual
].freeze
RAILS_ABSTRACT_SCHEMA_DEFINITIONS_HELPERS = %i[
column references belongs_to primary_key numeric
].freeze
RAILS_ABSTRACT_SCHEMA_DEFINITIONS_HELPERS = %i[column references belongs_to primary_key numeric].freeze
POSTGRES_SCHEMA_DEFINITIONS = %i[
bigserial bit bit_varying cidr citext daterange hstore inet interval
int4range int8range jsonb ltree macaddr money numrange oid point line

View File

@ -6,7 +6,7 @@ module RuboCop
module IndexMethod # rubocop:disable Metrics/ModuleLength
RESTRICT_ON_SEND = %i[each_with_object to_h map collect []].freeze
def on_block(node)
def on_block(node) # rubocop:todo InternalAffairs/NumblockHandler
on_bad_each_with_object(node) do |*match|
handle_possible_offense(node, match, 'each_with_object')
end
@ -98,10 +98,7 @@ module RuboCop
captures = extract_captures(correction.match)
correction.set_new_arg_name(captures.transformed_argname, corrector)
correction.set_new_body_expression(
captures.transforming_body_expr,
corrector
)
correction.set_new_body_expression(captures.transforming_body_expr, corrector)
end
# Internal helper class to hold match data
@ -110,8 +107,7 @@ module RuboCop
:transforming_body_expr
) do
def noop_transformation?
transforming_body_expr.lvar_type? &&
transforming_body_expr.children == [transformed_argname]
transforming_body_expr.lvar_type? && transforming_body_expr.children == [transformed_argname]
end
end
@ -157,17 +153,11 @@ module RuboCop
end
def set_new_arg_name(transformed_argname, corrector)
corrector.replace(
block_node.arguments.loc.expression,
"|#{transformed_argname}|"
)
corrector.replace(block_node.arguments.loc.expression, "|#{transformed_argname}|")
end
def set_new_body_expression(transforming_body_expr, corrector)
corrector.replace(
block_node.body.loc.expression,
transforming_body_expr.loc.expression.source
)
corrector.replace(block_node.body.loc.expression, transforming_body_expr.loc.expression.source)
end
end
end

View File

@ -0,0 +1,98 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Using `flash` assignment before `render` in Rails controllers will persist the message for too long.
# Check https://guides.rubyonrails.org/action_controller_overview.html#flash-now
#
# @safety
# This cop's autocorrection is unsafe because it replaces `flash` by `flash.now`.
# Even though it is usually a mistake, it might be used intentionally.
#
# @example
#
# # bad
# class HomeController < ApplicationController
# def create
# flash[:alert] = "msg"
# render :index
# end
# end
#
# # good
# class HomeController < ApplicationController
# def create
# flash.now[:alert] = "msg"
# render :index
# end
# end
#
class ActionControllerFlashBeforeRender < Base
extend AutoCorrector
MSG = 'Use `flash.now` before `render`.'
def_node_search :flash_assignment?, <<~PATTERN
^(send (send nil? :flash) :[]= ...)
PATTERN
def_node_search :render?, <<~PATTERN
(send nil? :render ...)
PATTERN
def_node_search :action_controller?, <<~PATTERN
{
(const nil? :ApplicationController)
(const (const nil? :ActionController) :Base)
}
PATTERN
RESTRICT_ON_SEND = [:flash].freeze
def on_send(flash_node)
return unless flash_assignment?(flash_node)
return unless followed_by_render?(flash_node)
return unless instance_method_or_block?(flash_node)
return unless inherit_action_controller_base?(flash_node)
add_offense(flash_node) do |corrector|
corrector.replace(flash_node, 'flash.now')
end
end
private
def followed_by_render?(flash_node)
flash_assigment_node = find_ancestor(flash_node, type: :send)
context = flash_assigment_node.parent
context.each_child_node.any? do |node|
render?(node)
end
end
def inherit_action_controller_base?(node)
class_node = find_ancestor(node, type: :class)
return unless class_node
action_controller?(class_node)
end
def instance_method_or_block?(node)
def_node = find_ancestor(node, type: :def)
block_node = find_ancestor(node, type: :block)
def_node || block_node
end
def find_ancestor(node, type:)
node.each_ancestor(type).first
end
end
end
end
end

View File

@ -69,7 +69,7 @@ module RuboCop
RESTRICT_ON_SEND = FILTER_METHODS + ACTION_METHODS
def on_block(node)
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
check_method_node(node.send_node)
end

View File

@ -21,10 +21,7 @@ module RuboCop
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
ALIASES = {
update_attributes: :update,
update_attributes!: :update!
}.freeze
ALIASES = { update_attributes: :update, update_attributes!: :update! }.freeze
RESTRICT_ON_SEND = ALIASES.keys.freeze

View File

@ -25,12 +25,9 @@ module RuboCop
# end
#
class ActiveRecordOverride < Base
MSG =
'Use %<prefer>s callbacks instead of overriding the Active Record ' \
'method `%<bad>s`.'
MSG = 'Use %<prefer>s callbacks instead of overriding the Active Record method `%<bad>s`.'
BAD_METHODS = %i[create destroy save update].freeze
ACTIVE_RECORD_CLASSES = %w[ApplicationRecord ActiveModel::Base
ActiveRecord::Base].freeze
ACTIVE_RECORD_CLASSES = %w[ApplicationRecord ActiveModel::Base ActiveRecord::Base].freeze
def on_def(node)
return unless BAD_METHODS.include?(node.method_name)

View File

@ -0,0 +1,70 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Checks for Rails framework classes that are patched directly instead of using Active Support load hooks. Direct
# patching forcibly loads the framework referenced, using hooks defers loading until it's actually needed.
#
# @safety
# While using lazy load hooks is recommended, it changes the order in which is code is loaded and may reveal
# load order dependency bugs.
#
# @example
#
# # bad
# ActiveRecord::Base.include(MyClass)
#
# # good
# ActiveSupport.on_load(:active_record) { include MyClass }
class ActiveSupportOnLoad < Base
extend AutoCorrector
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[prepend include extend].freeze
LOAD_HOOKS = {
'ActionCable' => 'action_cable',
'ActionCable::Channel::Base' => 'action_cable_channel',
'ActionCable::Connection::Base' => 'action_cable_connection',
'ActionCable::Connection::TestCase' => 'action_cable_connection_test_case',
'ActionController::API' => 'action_controller',
'ActionController::Base' => 'action_controller',
'ActionController::TestCase' => 'action_controller_test_case',
'ActionDispatch::IntegrationTest' => 'action_dispatch_integration_test',
'ActionDispatch::Request' => 'action_dispatch_request',
'ActionDispatch::Response' => 'action_dispatch_response',
'ActionDispatch::SystemTestCase' => 'action_dispatch_system_test_case',
'ActionMailbox::Base' => 'action_mailbox',
'ActionMailbox::InboundEmail' => 'action_mailbox_inbound_email',
'ActionMailbox::Record' => 'action_mailbox_record',
'ActionMailbox::TestCase' => 'action_mailbox_test_case',
'ActionMailer::Base' => 'action_mailer',
'ActionMailer::TestCase' => 'action_mailer_test_case',
'ActionText::Content' => 'action_text_content',
'ActionText::Record' => 'action_text_record',
'ActionText::RichText' => 'action_text_rich_text',
'ActionView::Base' => 'action_view',
'ActionView::TestCase' => 'action_view_test_case',
'ActiveJob::Base' => 'active_job',
'ActiveJob::TestCase' => 'active_job_test_case',
'ActiveRecord::Base' => 'active_record',
'ActiveStorage::Attachment' => 'active_storage_attachment',
'ActiveStorage::Blob' => 'active_storage_blob',
'ActiveStorage::Record' => 'active_storage_record',
'ActiveStorage::VariantRecord' => 'active_storage_variant_record',
'ActiveSupport::TestCase' => 'active_support_test_case'
}.freeze
def on_send(node)
receiver, method, arguments = *node # rubocop:disable InternalAffairs/NodeDestructuring
return unless receiver && (hook = LOAD_HOOKS[receiver.const_name])
preferred = "ActiveSupport.on_load(:#{hook}) { #{method} #{arguments.source} }"
add_offense(node, message: format(MSG, prefer: preferred, current: node.source)) do |corrector|
corrector.replace(node, preferred)
end
end
end
end
end
end

View File

@ -53,10 +53,7 @@ module RuboCop
private
def index_range(pair_node)
range_with_surrounding_comma(
range_with_surrounding_space(range: pair_node.loc.expression, side: :left),
:left
)
range_with_surrounding_comma(range_with_surrounding_space(pair_node.loc.expression, side: :left), :left)
end
end
end

View File

@ -63,8 +63,7 @@ module RuboCop
MSG_NIL_OR_EMPTY = 'Use `%<prefer>s` instead of `%<current>s`.'
MSG_NOT_PRESENT = 'Use `%<prefer>s` instead of `%<current>s`.'
MSG_UNLESS_PRESENT = 'Use `if %<prefer>s` instead of ' \
'`%<current>s`.'
MSG_UNLESS_PRESENT = 'Use `if %<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[!].freeze
# `(send nil $_)` is not actually a valid match for an offense. Nodes

View File

@ -111,25 +111,13 @@ module RuboCop
remove_timestamps
].freeze
MYSQL_COMBINABLE_TRANSFORMATIONS = %i[
rename
index
remove_index
].freeze
MYSQL_COMBINABLE_TRANSFORMATIONS = %i[rename index remove_index].freeze
MYSQL_COMBINABLE_ALTER_METHODS = %i[
rename_column
add_index
remove_index
].freeze
MYSQL_COMBINABLE_ALTER_METHODS = %i[rename_column add_index remove_index].freeze
POSTGRESQL_COMBINABLE_TRANSFORMATIONS = %i[
change_default
].freeze
POSTGRESQL_COMBINABLE_TRANSFORMATIONS = %i[change_default].freeze
POSTGRESQL_COMBINABLE_ALTER_METHODS = %i[
change_column_default
].freeze
POSTGRESQL_COMBINABLE_ALTER_METHODS = %i[change_column_default].freeze
def on_def(node)
return unless support_bulk_alter?
@ -186,8 +174,7 @@ module RuboCop
options = node.arguments[1]
return false unless options
options.hash_type? &&
options.keys.any? { |key| key.sym_type? && key.value == :bulk }
options.hash_type? && options.keys.any? { |key| key.sym_type? && key.value == :bulk }
end
def database
@ -237,8 +224,7 @@ module RuboCop
end
def call_to_combinable_alter_method?(child_node)
child_node.send_type? &&
combinable_alter_methods.include?(child_node.method_name)
child_node.send_type? && combinable_alter_methods.include?(child_node.method_name)
end
def combinable_alter_methods

View File

@ -93,7 +93,11 @@ module RuboCop
end
def offense_range(node)
end_pos = node.parent&.block_type? ? node.parent.loc.expression.end_pos : node.loc.expression.end_pos
end_pos = if node.parent&.block_type? && node.parent&.send_node == node
node.parent.loc.expression.end_pos
else
node.loc.expression.end_pos
end
range_between(node.loc.selector.begin_pos, end_pos)
end

View File

@ -37,9 +37,7 @@ module RuboCop
return if node.arguments.count >= 3
first_argument = node.first_argument
return if !first_argument ||
allowed_argument?(first_argument) ||
corrected_ancestor?(node)
return if !first_argument || allowed_argument?(first_argument) || corrected_ancestor?(node)
preferred_method = node.first_argument.value.to_s.underscore
message = format(MSG, preferred_method: preferred_method, current_argument: first_argument.source)

View File

@ -53,22 +53,17 @@ module RuboCop
class Date < Base
include ConfigurableEnforcedStyle
MSG = 'Do not use `Date.%<method_called>s` without zone. Use ' \
'`Time.zone.%<day>s` instead.'
MSG = 'Do not use `Date.%<method_called>s` without zone. Use `Time.zone.%<day>s` instead.'
MSG_SEND = 'Do not use `%<method>s` on Date objects, because they ' \
'know nothing about the time zone in use.'
MSG_SEND = 'Do not use `%<method>s` on Date objects, because they know nothing about the time zone in use.'
RESTRICT_ON_SEND = %i[to_time to_time_in_current_zone].freeze
BAD_DAYS = %i[today current yesterday tomorrow].freeze
DEPRECATED_METHODS = [
{ deprecated: 'to_time_in_current_zone', relevant: 'in_time_zone' }
].freeze
DEPRECATED_METHODS = [{ deprecated: 'to_time_in_current_zone', relevant: 'in_time_zone' }].freeze
DEPRECATED_MSG = '`%<deprecated>s` is deprecated. ' \
'Use `%<relevant>s` instead.'
DEPRECATED_MSG = '`%<deprecated>s` is deprecated. Use `%<relevant>s` instead.'
def on_const(node)
mod, klass = *node.children

View File

@ -93,15 +93,12 @@ module RuboCop
return false if arg_array.size != argument_array.size
arg_array.zip(argument_array).all? do |arg, argument|
arg.arg_type? &&
argument.lvar_type? &&
arg.children == argument.children
arg.arg_type? && argument.lvar_type? && arg.children == argument.children
end
end
def method_name_matches?(method_name, body)
method_name == body.method_name ||
(include_prefix_case? && method_name == prefixed_method_name(body))
method_name == body.method_name || (include_prefix_case? && method_name == prefixed_method_name(body))
end
def include_prefix_case?

View File

@ -37,7 +37,8 @@ module RuboCop
extend AutoCorrector
MSG = 'Avoid manipulating ActiveModel errors as hash directly.'
AUTOCORECTABLE_METHODS = %i[<< clear keys].freeze
AUTOCORRECTABLE_METHODS = %i[<< clear keys].freeze
INCOMPATIBLE_METHODS = %i[keys values to_h to_xml].freeze
MANIPULATIVE_METHODS = Set[
*%i[
@ -55,7 +56,7 @@ module RuboCop
{
#root_manipulation?
#root_assignment?
#errors_keys?
#errors_deprecated?
#messages_details_manipulation?
#messages_details_assignment?
}
@ -77,10 +78,10 @@ module RuboCop
...)
PATTERN
def_node_matcher :errors_keys?, <<~PATTERN
def_node_matcher :errors_deprecated?, <<~PATTERN
(send
(send #receiver_matcher :errors)
:keys)
{:keys :values :to_h :to_xml})
PATTERN
def_node_matcher :messages_details_manipulation?, <<~PATTERN
@ -106,10 +107,10 @@ module RuboCop
def on_send(node)
any_manipulation?(node) do
next if node.method?(:keys) && target_rails_version <= 6.0
next if target_rails_version <= 6.0 && INCOMPATIBLE_METHODS.include?(node.method_name)
add_offense(node) do |corrector|
next unless AUTOCORECTABLE_METHODS.include?(node.method_name)
next if skip_autocorrect?(node)
autocorrect(corrector, node)
end
@ -118,14 +119,16 @@ module RuboCop
private
def skip_autocorrect?(node)
return true unless AUTOCORRECTABLE_METHODS.include?(node.method_name)
return false unless (receiver = node.receiver.receiver)
receiver.send_type? && receiver.method?(:details) && node.method?(:<<)
end
def autocorrect(corrector, node)
receiver = node.receiver
if receiver.receiver.send_type? && receiver.receiver.method?(:messages)
corrector.remove(receiver.receiver.loc.dot)
corrector.remove(receiver.receiver.loc.selector)
end
range = offense_range(node, receiver)
replacement = replacement(node, receiver)
@ -133,11 +136,12 @@ module RuboCop
end
def offense_range(node, receiver)
range_between(receiver.receiver.source_range.end_pos, node.source_range.end_pos)
receiver = receiver.receiver while receiver.send_type? && !receiver.method?(:errors) && receiver.receiver
range_between(receiver.source_range.end_pos, node.source_range.end_pos)
end
def replacement(node, receiver)
return '.errors.attribute_names' if node.method?(:keys)
return '.attribute_names' if node.method?(:keys)
key = receiver.first_argument.source

View File

@ -37,7 +37,7 @@ module RuboCop
add_offense(scope_node) do |corrector|
# Eat the comma on the left.
range = range_with_surrounding_space(range: scope_node.source_range, side: :left)
range = range_with_surrounding_space(scope_node.source_range, side: :left)
range = range_with_surrounding_comma(range, :left)
corrector.remove(range)

View File

@ -70,8 +70,7 @@ module RuboCop
end
def allowed_invocation?(node)
allowed_method?(node) || allowed_receiver?(node) ||
whitelisted?(node)
allowed_method?(node) || allowed_receiver?(node) || whitelisted?(node)
end
def allowed_method?(node)
@ -95,8 +94,7 @@ module RuboCop
end
def autocorrect_method_name(corrector, node)
corrector.replace(node.loc.selector,
static_method_name(node.method_name.to_s))
corrector.replace(node.loc.selector, static_method_name(node.method_name.to_s))
end
def autocorrect_argument_keywords(corrector, node, keywords)

View File

@ -20,8 +20,7 @@ module RuboCop
class EnumUniqueness < Base
include Duplication
MSG = 'Duplicate value `%<value>s` found in `%<enum>s` ' \
'enum declaration.'
MSG = 'Duplicate value `%<value>s` found in `%<enum>s` enum declaration.'
RESTRICT_ON_SEND = %i[enum].freeze
def_node_matcher :enum?, <<~PATTERN
@ -41,9 +40,7 @@ module RuboCop
next unless duplicates?(items)
consecutive_duplicates(items).each do |item|
add_offense(item, message: format(
MSG, value: item.source, enum: enum_name(key)
))
add_offense(item, message: format(MSG, value: item.source, enum: enum_name(key)))
end
end
end

View File

@ -96,8 +96,7 @@ module RuboCop
end
def rails_env_on_lhs?(node)
comparing_str_env_with_rails_env_on_lhs?(node) ||
comparing_sym_env_with_rails_env_on_lhs?(node)
comparing_str_env_with_rails_env_on_lhs?(node) || comparing_sym_env_with_rails_env_on_lhs?(node)
end
def build_predicate_method_for_rails_env_on_lhs(node)

View File

@ -50,8 +50,7 @@ module RuboCop
return unless node.children.last.str_type?
last_child_source = node.children.last.source
return unless last_child_source.start_with?('.') ||
last_child_source.include?(File::SEPARATOR)
return unless last_child_source.start_with?('.') || last_child_source.include?(File::SEPARATOR)
return if last_child_source.start_with?(':')
register_offense(node)
@ -97,8 +96,7 @@ module RuboCop
def register_offense(node)
line_range = node.loc.column...node.loc.last_column
source_range = source_range(processed_source.buffer, node.first_line,
line_range)
source_range = source_range(processed_source.buffer, node.first_line, line_range)
add_offense(source_range)
end

View File

@ -13,11 +13,17 @@ module RuboCop
# # good
# User.all.find_each
#
# @example IgnoredMethods: ['order']
# @example AllowedMethods: ['order']
# # good
# User.order(:foo).each
#
# @example AllowedPattern: [/order/]
# # good
# User.order(:foo).each
class FindEach < Base
include ActiveRecordHelper
include AllowedMethods
include AllowedPattern
extend AutoCorrector
MSG = 'Use `find_each` instead of `each`.'
@ -47,7 +53,7 @@ module RuboCop
method_chain = node.each_node(:send).map(&:method_name)
(cop_config['IgnoredMethods'].map(&:to_sym) & method_chain).any?
method_chain.any? { |method_name| allowed_method?(method_name) || matches_allowed_pattern?(method_name) }
end
def active_model_error_where?(node)

View File

@ -0,0 +1,69 @@
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Identifies usages of `travel_to` with an argument of the current time and
# change them to use `freeze_time` instead.
#
# @safety
# This cops autocorrection is unsafe because `freeze_time` just delegates to
# `travel_to` with a default `Time.now`, it is not strictly equivalent to `Time.now`
# if the argument of `travel_to` is the current time considering time zone.
#
# @example
# # bad
# travel_to(Time.now)
# travel_to(Time.new)
# travel_to(DateTime.now)
# travel_to(Time.current)
# travel_to(Time.zone.now)
# travel_to(Time.now.in_time_zone)
# travel_to(Time.current.to_time)
#
# # good
# freeze_time
#
class FreezeTime < Base
extend AutoCorrector
MSG = 'Use `freeze_time` instead of `travel_to`.'
NOW_METHODS = %i[now new current].freeze
CONV_METHODS = %i[to_time in_time_zone].freeze
RESTRICT_ON_SEND = %i[travel_to].freeze
# @!method time_now?(node)
def_node_matcher :time_now?, <<~PATTERN
(const nil? {:Time :DateTime})
PATTERN
# @!method zoned_time_now?(node)
def_node_matcher :zoned_time_now?, <<~PATTERN
(send (const nil? :Time) :zone)
PATTERN
def on_send(node)
child_node, method_name = *node.first_argument.children
return unless current_time?(child_node, method_name) || current_time_with_convert?(child_node, method_name)
add_offense(node) { |corrector| corrector.replace(node, 'freeze_time') }
end
private
def current_time?(node, method_name)
return false unless NOW_METHODS.include?(method_name)
node.send_type? ? zoned_time_now?(node) : time_now?(node)
end
def current_time_with_convert?(node, method_name)
return false unless CONV_METHODS.include?(method_name)
child_node, child_method_name = *node.children
current_time?(child_node, child_method_name)
end
end
end
end
end

View File

@ -105,9 +105,7 @@ module RuboCop
return false unless node.parent
return true if contain_valid_options_in_with_options_block?(
node.parent.parent
)
return true if contain_valid_options_in_with_options_block?(node.parent.parent)
end
false

View File

@ -22,11 +22,8 @@ module RuboCop
extend AutoCorrector
extend TargetRailsVersion
MSG = 'Use keyword arguments instead of ' \
'positional arguments for http call: `%<verb>s`.'
KEYWORD_ARGS = %i[
method params session body flash xhr as headers env to
].freeze
MSG = 'Use keyword arguments instead of positional arguments for http call: `%<verb>s`.'
KEYWORD_ARGS = %i[method params session body flash xhr as headers env to].freeze
ROUTING_METHODS = %i[draw routes].freeze
RESTRICT_ON_SEND = %i[get post put patch delete head].freeze
@ -75,8 +72,7 @@ module RuboCop
return false if kwsplat_hash?(data)
data.each_pair.none? do |pair|
special_keyword_arg?(pair.key) ||
(format_arg?(pair.key) && data.pairs.one?)
special_keyword_arg?(pair.key) || (format_arg?(pair.key) && data.pairs.one?)
end
end
@ -98,8 +94,7 @@ module RuboCop
return '' if data.hash_type? && data.empty?
hash_data = if data.hash_type?
format('{ %<data>s }',
data: data.pairs.map(&:source).join(', '))
format('{ %<data>s }', data: data.pairs.map(&:source).join(', '))
else
# user supplies an object,
# no need to surround with braces

View File

@ -84,10 +84,8 @@ module RuboCop
# :nodoc:
class SymbolicStyleChecker
MSG = 'Prefer `%<prefer>s` over `%<current>s` ' \
'to define HTTP status code.'
DEFAULT_MSG = 'Prefer `symbolic` over `numeric` ' \
'to define HTTP status code.'
MSG = 'Prefer `%<prefer>s` over `%<current>s` to define HTTP status code.'
DEFAULT_MSG = 'Prefer `symbolic` over `numeric` to define HTTP status code.'
attr_reader :node
@ -118,17 +116,14 @@ module RuboCop
end
def custom_http_status_code?
node.int_type? &&
!::Rack::Utils::SYMBOL_TO_STATUS_CODE.value?(number)
node.int_type? && !::Rack::Utils::SYMBOL_TO_STATUS_CODE.value?(number)
end
end
# :nodoc:
class NumericStyleChecker
MSG = 'Prefer `%<prefer>s` over `%<current>s` ' \
'to define HTTP status code.'
DEFAULT_MSG = 'Prefer `numeric` over `symbolic` ' \
'to define HTTP status code.'
MSG = 'Prefer `%<prefer>s` over `%<current>s` to define HTTP status code.'
DEFAULT_MSG = 'Prefer `numeric` over `symbolic` to define HTTP status code.'
PERMITTED_STATUS = %i[error success missing redirect].freeze
attr_reader :node

View File

@ -42,12 +42,7 @@ module RuboCop
`%<ignore>s` option will be ignored when `%<prefer>s` and `%<ignore>s` are used together.
MSG
RESTRICT_ON_SEND = %i[
skip_after_action
skip_around_action
skip_before_action
skip_action_callback
].freeze
RESTRICT_ON_SEND = %i[skip_after_action skip_around_action skip_before_action skip_action_callback].freeze
FILTERS = RESTRICT_ON_SEND.map { |method_name| ":#{method_name}" }
@ -67,11 +62,9 @@ module RuboCop
options = options_hash(options)
if if_and_only?(options)
add_offense(options[:if],
message: format(MSG, prefer: :only, ignore: :if))
add_offense(options[:if], message: format(MSG, prefer: :only, ignore: :if))
elsif if_and_except?(options)
add_offense(options[:except],
message: format(MSG, prefer: :if, ignore: :except))
add_offense(options[:except], message: format(MSG, prefer: :if, ignore: :except))
end
end

View File

@ -192,8 +192,7 @@ module RuboCop
end
return if options_ignoring_inverse_of?(options)
return unless scope?(arguments) ||
options_requiring_inverse_of?(options)
return unless scope?(arguments) || options_requiring_inverse_of?(options)
return if options_contain_inverse_of?(options)
@ -206,8 +205,7 @@ module RuboCop
def options_requiring_inverse_of?(options)
required = options.any? do |opt|
conditions_option?(opt) ||
foreign_key_option?(opt)
conditions_option?(opt) || foreign_key_option?(opt)
end
return required if target_rails_version >= 5.2
@ -227,8 +225,7 @@ module RuboCop
def with_options_arguments(recv, node)
blocks = node.each_ancestor(:block).select do |block|
block.send_node.command?(:with_options) &&
same_context_in_with_options?(block.arguments.first, recv)
block.send_node.command?(:with_options) && same_context_in_with_options?(block.arguments.first, recv)
end
blocks.flat_map { |n| n.send_node.arguments }
end

View File

@ -184,13 +184,9 @@ module RuboCop
# @return [String]
def message(methods, parent)
if methods.size == 1
format(MSG,
action: "`#{methods[0]}` is",
type: parent.type)
format(MSG, action: "`#{methods[0]}` is", type: parent.type)
else
format(MSG,
action: "`#{methods.join('`, `')}` are",
type: parent.type)
format(MSG, action: "`#{methods.join('`, `')}` are", type: parent.type)
end
end
end

View File

@ -68,10 +68,7 @@ module RuboCop
def append_to_rel(rel_node, corrector)
existing_rel = rel_node.children.last.value
str_range = rel_node.children.last.loc.expression.adjust(
begin_pos: 1,
end_pos: -1
)
str_range = rel_node.children.last.loc.expression.adjust(begin_pos: 1, end_pos: -1)
corrector.replace(str_range, "#{existing_rel} noopener")
end

View File

@ -21,11 +21,8 @@ module RuboCop
include RangeHelp
extend AutoCorrector
MSG = 'Do not write to stdout. ' \
"Use Rails's logger if you want to log."
RESTRICT_ON_SEND = %i[
ap p pp pretty_print print puts binwrite syswrite write write_nonblock
].freeze
MSG = "Do not write to stdout. Use Rails's logger if you want to log."
RESTRICT_ON_SEND = %i[ap p pp pretty_print print puts binwrite syswrite write write_nonblock].freeze
def_node_matcher :output?, <<~PATTERN
(send nil? {:ap :p :pp :pretty_print :print :puts} ...)

View File

@ -94,8 +94,7 @@ module RuboCop
end
def duration_method?(method_name)
SINGULAR_DURATION_METHODS.key?(method_name) ||
PLURAL_DURATION_METHODS.key?(method_name)
SINGULAR_DURATION_METHODS.key?(method_name) || PLURAL_DURATION_METHODS.key?(method_name)
end
end
end

View File

@ -106,9 +106,7 @@ module RuboCop
end
def message(node, receiver, other)
format(MSG,
prefer: replacement(receiver, other),
current: node.source)
format(MSG, prefer: replacement(receiver, other), current: node.source)
end
def replacement(receiver, other)

View File

@ -47,10 +47,8 @@ module RuboCop
extend AutoCorrector
MSG_NOT_BLANK = 'Use `%<prefer>s` instead of `%<current>s`.'
MSG_EXISTS_AND_NOT_EMPTY = 'Use `%<prefer>s` instead of ' \
'`%<current>s`.'
MSG_UNLESS_BLANK = 'Use `if %<prefer>s` instead of ' \
'`%<current>s`.'
MSG_EXISTS_AND_NOT_EMPTY = 'Use `%<prefer>s` instead of `%<current>s`.'
MSG_UNLESS_BLANK = 'Use `if %<prefer>s` instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[!].freeze
def_node_matcher :exists_and_not_empty?, <<~PATTERN
@ -118,8 +116,7 @@ module RuboCop
unless_blank?(node) do |method_call, receiver|
range = unless_condition(node, method_call)
msg = format(MSG_UNLESS_BLANK, prefer: replacement(receiver),
current: range.source)
msg = format(MSG_UNLESS_BLANK, prefer: replacement(receiver), current: range.source)
add_offense(range, message: msg) do |corrector|
autocorrect(corrector, node)
end

View File

@ -39,7 +39,7 @@ module RuboCop
(block $(send nil? :task ...) ...)
PATTERN
def on_block(node)
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
task_definition?(node) do |task_method|
return if task_name(task_method) == :default
return if with_dependencies?(task_method)

View File

@ -30,11 +30,9 @@ module RuboCop
include RangeHelp
extend AutoCorrector
MSG_SAME =
'`allow_nil` is redundant when `allow_blank` has the same value.'
MSG_SAME = '`allow_nil` is redundant when `allow_blank` has the same value.'
MSG_ALLOW_NIL_FALSE =
'`allow_nil: false` is redundant when `allow_blank` is true.'
MSG_ALLOW_NIL_FALSE = '`allow_nil: false` is redundant when `allow_blank` is true.'
RESTRICT_ON_SEND = %i[validates].freeze

View File

@ -41,7 +41,7 @@ module RuboCop
association_with_foreign_key(node) do |type, name, options, foreign_key_pair, foreign_key|
if redundant?(node, type, name, options, foreign_key)
add_offense(foreign_key_pair.loc.expression) do |corrector|
range = range_with_surrounding_space(range: foreign_key_pair.source_range, side: :left)
range = range_with_surrounding_space(foreign_key_pair.source_range, side: :left)
range = range_with_surrounding_comma(range, :left)
corrector.remove(range)

View File

@ -217,7 +217,7 @@ module RuboCop
keys.each do |key|
key_node = node.arguments.find { |arg| arg.value == key }
key_range = range_with_surrounding_space(
range: range_with_surrounding_comma(key_node.source_range, :right),
range_with_surrounding_comma(key_node.source_range, :right),
side: :right
)
corrector.remove(key_range)
@ -226,7 +226,7 @@ module RuboCop
def remove_presence_option(corrector, presence)
range = range_with_surrounding_comma(
range_with_surrounding_space(range: presence.source_range, side: :left),
range_with_surrounding_space(presence.source_range, side: :left),
:left
)
corrector.remove(range)

View File

@ -60,15 +60,6 @@ module RuboCop
MSG = 'Redundant receiver in `with_options`.'
def_node_matcher :with_options?, <<~PATTERN
(block
(send nil? :with_options
(...))
(args
$_arg)
$_body)
PATTERN
def_node_search :all_block_nodes_in, <<~PATTERN
(block ...)
PATTERN
@ -78,29 +69,40 @@ module RuboCop
PATTERN
def on_block(node)
with_options?(node) do |arg, body|
return if body.nil?
return unless all_block_nodes_in(body).count.zero?
return unless node.method?(:with_options)
return unless (body = node.body)
return unless all_block_nodes_in(body).count.zero?
send_nodes = all_send_nodes_in(body)
send_nodes = all_send_nodes_in(body)
return unless redundant_receiver?(send_nodes, node)
if send_nodes.all? { |n| same_value?(arg, n.receiver) }
send_nodes.each do |send_node|
receiver = send_node.receiver
add_offense(receiver.source_range) do |corrector|
autocorrect(corrector, send_node)
end
end
send_nodes.each do |send_node|
receiver = send_node.receiver
add_offense(receiver.source_range) do |corrector|
autocorrect(corrector, send_node, node)
end
end
end
alias on_numblock on_block
private
def autocorrect(corrector, node)
corrector.remove(node.receiver.source_range)
corrector.remove(node.loc.dot)
corrector.remove(block_argument_range(node))
def autocorrect(corrector, send_node, node)
corrector.remove(send_node.receiver.source_range)
corrector.remove(send_node.loc.dot)
corrector.remove(block_argument_range(send_node)) unless node.numblock_type?
end
def redundant_receiver?(send_nodes, node)
proc = if node.numblock_type?
->(n) { n.receiver.lvar_type? && n.receiver.source == '_1' }
else
arg = node.arguments.first
->(n) { same_value?(arg, n.receiver) }
end
send_nodes.all?(&proc)
end
def block_argument_range(node)

View File

@ -34,12 +34,29 @@ module RuboCop
def on_send(node)
association_with_reflection(node) do |reflection_class_name|
return if reflection_class_name.value.send_type? && reflection_class_name.value.receiver.nil?
return if reflection_class_name.value.lvar_type? && str_assigned?(reflection_class_name)
add_offense(reflection_class_name.loc.expression)
end
end
private
def str_assigned?(reflection_class_name)
lvar = reflection_class_name.value.source
reflection_class_name.ancestors.each do |nodes|
return true if nodes.each_child_node(:lvasgn).detect do |node|
lhs, rhs = *node
lhs.to_s == lvar && ALLOWED_REFLECTION_CLASS_TYPES.include?(rhs.type)
end
end
false
end
def reflection_class_value?(class_value)
if class_value.send_type?
!class_value.method?(:to_s) || class_value.receiver&.const_type?

View File

@ -81,11 +81,7 @@ module RuboCop
end
def offense_message(method_name)
format(
MSG,
bad_method: method_name,
good_method: convert_good_method(method_name)
)
format(MSG, bad_method: method_name, good_method: convert_good_method(method_name))
end
def convert_good_method(bad_method)

View File

@ -34,8 +34,7 @@ module RuboCop
include RangeHelp
extend AutoCorrector
MSG = 'Do not assign `%<method_name>s` to constants as it ' \
'will be evaluated only once.'
MSG = 'Do not assign `%<method_name>s` to constants as it will be evaluated only once.'
RELATIVE_DATE_METHODS = %i[since from_now after ago until before yesterday tomorrow].to_set.freeze
def on_casgn(node)
@ -77,9 +76,7 @@ module RuboCop
return unless scope.nil?
indent = ' ' * node.loc.column
new_code = ["def self.#{const_name.downcase}",
"#{indent}#{value.source}",
'end'].join("\n#{indent}")
new_code = ["def self.#{const_name.downcase}", "#{indent}#{value.source}", 'end'].join("\n#{indent}")
corrector.replace(node.source_range, new_code)
end

Some files were not shown because too many files have changed in this diff Show More