repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/class_vars.rb | lib/rubocop/cop/style/class_vars.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of class variables. Offenses
# are signaled only on assignment to class variables to
# reduce the number of offenses that would be reported.
#
# You have to be careful when setting a value for a class
# variable; if a class has been inherited, changing the
# value of a class variable also affects the inheriting
# classes. This means that it's almost always better to
# use a class instance variable instead.
#
# @example
# # bad
# class A
# @@test = 10
# end
#
# class A
# def self.test(name, value)
# class_variable_set("@@#{name}", value)
# end
# end
#
# class A; end
# A.class_variable_set(:@@test, 10)
#
# # good
# class A
# @test = 10
# end
#
# class A
# def test
# @@test # you can access class variable without offense
# end
# end
#
# class A
# def self.test(name)
# class_variable_get("@@#{name}") # you can access without offense
# end
# end
#
class ClassVars < Base
MSG = 'Replace class var %<class_var>s with a class instance var.'
RESTRICT_ON_SEND = %i[class_variable_set].freeze
def on_cvasgn(node)
add_offense(node.loc.name, message: format(MSG, class_var: node.children.first))
end
def on_send(node)
return unless (first_argument = node.first_argument)
add_offense(first_argument, message: format(MSG, class_var: first_argument.source))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/empty_lambda_parameter.rb | lib/rubocop/cop/style/empty_lambda_parameter.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for parentheses for empty lambda parameters. Parentheses
# for empty lambda parameters do not cause syntax errors, but they are
# redundant.
#
# @example
# # bad
# -> () { do_something }
#
# # good
# -> { do_something }
#
# # good
# -> (arg) { do_something(arg) }
class EmptyLambdaParameter < Base
include EmptyParameter
include RangeHelp
extend AutoCorrector
MSG = 'Omit parentheses for the empty lambda parameters.'
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
send_node = node.send_node
return unless send_node.send_type?
check(node) if node.send_node.lambda_literal?
end
private
def autocorrect(corrector, node)
send_node = node.parent.send_node
range = range_between(send_node.source_range.end_pos, node.source_range.end_pos)
corrector.remove(range)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/float_division.rb | lib/rubocop/cop/style/float_division.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for division with integers coerced to floats.
# It is recommended to either always use `fdiv` or coerce one side only.
# This cop also provides other options for code consistency.
#
# For `Regexp.last_match` and nth reference (e.g., `$1`), it assumes that the value
# is a string matched by a regular expression, and allows conversion with `#to_f`.
#
# @safety
# This cop is unsafe, because if the operand variable is a string object
# then `#to_f` will be removed and an error will occur.
#
# [source,ruby]
# ----
# a = '1.2'
# b = '3.4'
# a.to_f / b.to_f # Both `to_f` calls are required here
# ----
#
# @example EnforcedStyle: single_coerce (default)
# # bad
# a.to_f / b.to_f
#
# # good
# a.to_f / b
# a / b.to_f
#
# @example EnforcedStyle: left_coerce
# # bad
# a / b.to_f
# a.to_f / b.to_f
#
# # good
# a.to_f / b
#
# @example EnforcedStyle: right_coerce
# # bad
# a.to_f / b
# a.to_f / b.to_f
#
# # good
# a / b.to_f
#
# @example EnforcedStyle: fdiv
# # bad
# a / b.to_f
# a.to_f / b
# a.to_f / b.to_f
#
# # good
# a.fdiv(b)
class FloatDivision < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MESSAGES = {
left_coerce: 'Prefer using `.to_f` on the left side.',
right_coerce: 'Prefer using `.to_f` on the right side.',
single_coerce: 'Prefer using `.to_f` on one side only.',
fdiv: 'Prefer using `fdiv` for float divisions.'
}.freeze
RESTRICT_ON_SEND = %i[/].freeze
# @!method right_coerce?(node)
def_node_matcher :right_coerce?, <<~PATTERN
(send _ :/ #to_f_method?)
PATTERN
# @!method left_coerce?(node)
def_node_matcher :left_coerce?, <<~PATTERN
(send #to_f_method? :/ _)
PATTERN
# @!method both_coerce?(node)
def_node_matcher :both_coerce?, <<~PATTERN
(send #to_f_method? :/ #to_f_method?)
PATTERN
# @!method any_coerce?(node)
def_node_matcher :any_coerce?, <<~PATTERN
{(send _ :/ #to_f_method?) (send #to_f_method? :/ _)}
PATTERN
# @!method to_f_method?(node)
def_node_matcher :to_f_method?, <<~PATTERN
(send !nil? :to_f)
PATTERN
# @!method regexp_last_match?(node)
def_node_matcher :regexp_last_match?, <<~PATTERN
{
(send (const {nil? cbase} :Regexp) :last_match int)
(:nth_ref _)
}
PATTERN
def on_send(node)
return unless offense_condition?(node)
add_offense(node) do |corrector|
case style
when :left_coerce, :single_coerce
add_to_f_method(corrector, node.receiver)
remove_to_f_method(corrector, node.first_argument)
when :right_coerce
remove_to_f_method(corrector, node.receiver)
add_to_f_method(corrector, node.first_argument)
when :fdiv
correct_from_slash_to_fdiv(corrector, node, node.receiver, node.first_argument)
end
end
end
private
def offense_condition?(node)
return false if regexp_last_match?(node.receiver.receiver) ||
regexp_last_match?(node.first_argument.receiver)
case style
when :left_coerce
right_coerce?(node)
when :right_coerce
left_coerce?(node)
when :single_coerce
both_coerce?(node)
when :fdiv
any_coerce?(node)
else
false
end
end
def message(_node)
MESSAGES[style]
end
def add_to_f_method(corrector, node)
corrector.insert_after(node, '.to_f') unless node.send_type? && node.method?(:to_f)
end
def remove_to_f_method(corrector, send_node)
corrector.remove(send_node.loc.dot)
corrector.remove(send_node.loc.selector)
end
def correct_from_slash_to_fdiv(corrector, node, receiver, argument)
receiver_source = extract_receiver_source(receiver)
argument_source = extract_receiver_source(argument)
if argument.respond_to?(:parenthesized?) && !argument.parenthesized?
argument_source = "(#{argument_source})"
end
corrector.replace(node, "#{receiver_source}.fdiv#{argument_source}")
end
def extract_receiver_source(node)
if node.send_type? && node.method?(:to_f)
node.receiver.source
else
node.source
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/invertible_unless_condition.rb | lib/rubocop/cop/style/invertible_unless_condition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for usages of `unless` which can be replaced by `if` with inverted condition.
# Code without `unless` is easier to read, but that is subjective, so this cop
# is disabled by default.
#
# Methods that can be inverted should be defined in `InverseMethods`. Note that
# the relationship of inverse methods needs to be defined in both directions.
# For example,
#
# [source,yaml]
# ----
# InverseMethods:
# :!=: :==
# :even?: :odd?
# :odd?: :even?
# ----
#
# will suggest both `even?` and `odd?` to be inverted, but only `!=` (and not `==`).
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the method
# and its inverse method are both defined on receiver, and also are
# actually inverse of each other.
#
# @example
# # bad (simple condition)
# foo unless !bar
# foo unless x != y
# foo unless x >= 10
# foo unless x.even?
# foo unless odd?
#
# # good
# foo if bar
# foo if x == y
# foo if x < 10
# foo if x.odd?
# foo if even?
#
# # bad (complex condition)
# foo unless x != y || x.even?
#
# # good
# foo if x == y && x.odd?
#
# # good (if)
# foo if !condition
#
class InvertibleUnlessCondition < Base
extend AutoCorrector
MSG = 'Prefer `%<prefer>s` over `%<current>s`.'
def on_if(node)
return unless node.unless?
condition = node.condition
return unless invertible?(condition)
message = format(MSG, prefer: "#{node.inverse_keyword} #{preferred_condition(condition)}",
current: "#{node.keyword} #{condition.source}")
add_offense(node, message: message) do |corrector|
corrector.replace(node.loc.keyword, node.inverse_keyword)
autocorrect(corrector, condition)
end
end
private
def invertible?(node) # rubocop:disable Metrics/CyclomaticComplexity
case node&.type
when :begin
invertible?(node.children.first)
when :send
return false if inheritance_check?(node)
node.method?(:!) || inverse_methods.key?(node.method_name)
when :or, :and
invertible?(node.lhs) && invertible?(node.rhs)
else
false
end
end
def inheritance_check?(node)
argument = node.first_argument
node.method?(:<) && argument.const_type? &&
argument.short_name.to_s.upcase != argument.short_name.to_s
end
def preferred_condition(node)
case node.type
when :begin then "(#{preferred_condition(node.children.first)})"
when :send then preferred_send_condition(node)
when :or, :and then preferred_logical_condition(node)
end
end
def preferred_send_condition(node) # rubocop:disable Metrics/CyclomaticComplexity
receiver_source = node.receiver&.source
return receiver_source if node.method?(:!)
# receiver may be implicit (self)
dotted_receiver_source = receiver_source ? "#{receiver_source}." : ''
inverse_method_name = inverse_methods[node.method_name]
return "#{dotted_receiver_source}#{inverse_method_name}" unless node.arguments?
argument_list = node.arguments.map(&:source).join(', ')
if node.operator_method?
return "#{receiver_source} #{inverse_method_name} #{argument_list}"
end
if node.parenthesized?
return "#{dotted_receiver_source}#{inverse_method_name}(#{argument_list})"
end
"#{dotted_receiver_source}#{inverse_method_name} #{argument_list}"
end
def preferred_logical_condition(node)
preferred_lhs = preferred_condition(node.lhs)
preferred_rhs = preferred_condition(node.rhs)
"#{preferred_lhs} #{node.inverse_operator} #{preferred_rhs}"
end
def autocorrect(corrector, node)
case node.type
when :begin
autocorrect(corrector, node.children.first)
when :send
autocorrect_send_node(corrector, node)
when :or, :and
corrector.replace(node.loc.operator, node.inverse_operator)
autocorrect(corrector, node.lhs)
autocorrect(corrector, node.rhs)
end
end
def autocorrect_send_node(corrector, node)
if node.method?(:!)
corrector.remove(node.loc.selector)
else
corrector.replace(node.loc.selector, inverse_methods[node.method_name])
end
end
def inverse_methods
@inverse_methods ||= cop_config['InverseMethods']
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/missing_else.rb | lib/rubocop/cop/style/missing_else.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for `if` expressions that do not have an `else` branch.
#
# NOTE: Pattern matching is allowed to have no `else` branch because unlike `if` and `case`,
# it raises `NoMatchingPatternError` if the pattern doesn't match and without having `else`.
#
# Supported styles are: if, case, both.
#
# @example EnforcedStyle: both (default)
# # warn when an `if` or `case` expression is missing an `else` branch.
#
# # bad
# if condition
# statement
# end
#
# # bad
# case var
# when condition
# statement
# end
#
# # good
# if condition
# statement
# else
# # the content of `else` branch will be determined by Style/EmptyElse
# end
#
# # good
# case var
# when condition
# statement
# else
# # the content of `else` branch will be determined by Style/EmptyElse
# end
#
# @example EnforcedStyle: if
# # warn when an `if` expression is missing an `else` branch.
#
# # bad
# if condition
# statement
# end
#
# # good
# if condition
# statement
# else
# # the content of `else` branch will be determined by Style/EmptyElse
# end
#
# # good
# case var
# when condition
# statement
# end
#
# # good
# case var
# when condition
# statement
# else
# # the content of `else` branch will be determined by Style/EmptyElse
# end
#
# @example EnforcedStyle: case
# # warn when a `case` expression is missing an `else` branch.
#
# # bad
# case var
# when condition
# statement
# end
#
# # good
# case var
# when condition
# statement
# else
# # the content of `else` branch will be determined by Style/EmptyElse
# end
#
# # good
# if condition
# statement
# end
#
# # good
# if condition
# statement
# else
# # the content of `else` branch will be determined by Style/EmptyElse
# end
class MissingElse < Base
include OnNormalIfUnless
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = '`%<type>s` condition requires an `else`-clause.'
MSG_NIL = '`%<type>s` condition requires an `else`-clause with `nil` in it.'
MSG_EMPTY = '`%<type>s` condition requires an empty `else`-clause.'
def on_normal_if_unless(node)
return if case_style?
return if unless_else_cop_enabled? && node.unless?
check(node)
end
def on_case(node)
return if if_style?
check(node)
end
def on_case_match(node)
# do nothing.
end
private
def check(node)
return if node.else?
add_offense(node, message: format(message_template, type: node.type)) do |corrector|
autocorrect(corrector, node)
end
end
def message_template
case empty_else_style
when :empty
MSG_NIL
when :nil
MSG_EMPTY
else
MSG
end
end
def autocorrect(corrector, node)
node = node.ancestors.find { |ancestor| ancestor.loc.end } unless node.loc.end
case empty_else_style
when :empty
corrector.insert_before(node.loc.end, 'else; nil; ')
when :nil
corrector.insert_before(node.loc.end, 'else; ')
end
end
def if_style?
style == :if
end
def case_style?
style == :case
end
def unless_else_cop_enabled?
unless_else_config.fetch('Enabled')
end
def unless_else_config
config.for_cop('Style/UnlessElse')
end
def empty_else_style
return unless empty_else_config.key?('EnforcedStyle')
empty_else_config['EnforcedStyle'].to_sym
end
def empty_else_config
config.for_cop('Style/EmptyElse')
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/nested_ternary_operator.rb | lib/rubocop/cop/style/nested_ternary_operator.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for nested ternary op expressions.
#
# @example
# # bad
# a ? (b ? b1 : b2) : a2
#
# # good
# if a
# b ? b1 : b2
# else
# a2
# end
class NestedTernaryOperator < Base
extend AutoCorrector
include RangeHelp
MSG = 'Ternary operators must not be nested. Prefer `if` or `else` constructs instead.'
def on_if(node)
return unless node.ternary?
node.each_descendant(:if).select(&:ternary?).each do |nested_ternary|
add_offense(nested_ternary) do |corrector|
next if part_of_ignored_node?(node)
autocorrect(corrector, node)
ignore_node(node)
end
end
end
private
def autocorrect(corrector, if_node)
replace_loc_and_whitespace(corrector, if_node.loc.question, "\n")
replace_loc_and_whitespace(corrector, if_node.loc.colon, "\nelse\n")
corrector.replace(if_node.if_branch, remove_parentheses(if_node.if_branch.source))
corrector.wrap(if_node, 'if ', "\nend")
end
def remove_parentheses(source)
if source.start_with?('(') && source.end_with?(')')
source.delete_prefix('(').delete_suffix(')')
else
source
end
end
def replace_loc_and_whitespace(corrector, range, replacement)
corrector.replace(
range_with_surrounding_space(range: range, whitespace: true),
replacement
)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/bisected_attr_accessor.rb | lib/rubocop/cop/style/bisected_attr_accessor.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where `attr_reader` and `attr_writer`
# for the same method can be combined into single `attr_accessor`.
#
# @example
# # bad
# class Foo
# attr_reader :bar
# attr_writer :bar
# end
#
# # good
# class Foo
# attr_accessor :bar
# end
#
class BisectedAttrAccessor < Base
require_relative 'bisected_attr_accessor/macro'
include RangeHelp
extend AutoCorrector
MSG = 'Combine both accessors into `attr_accessor %<name>s`.'
def on_new_investigation
@macros_to_rewrite = {}
end
def on_class(class_node)
@macros_to_rewrite[class_node] = Set.new
find_macros(class_node.body).each_value do |macros|
bisected = find_bisection(macros)
next unless bisected.any?
macros.each do |macro|
attrs = macro.bisect(*bisected)
next if attrs.none?
@macros_to_rewrite[class_node] << macro
attrs.each { |attr| register_offense(attr) }
end
end
end
alias on_sclass on_class
alias on_module on_class
# Each offending macro is captured and registered in `on_class` but correction
# happens in `after_class` because a macro might have multiple attributes
# rewritten from it
def after_class(class_node)
@macros_to_rewrite[class_node].each do |macro|
node = macro.node
range = range_by_whole_lines(node.source_range, include_final_newline: true)
correct(range) do |corrector|
if macro.writer?
correct_writer(corrector, macro, node, range)
else
correct_reader(corrector, macro, node, range)
end
end
end
end
alias after_sclass after_class
alias after_module after_class
private
def find_macros(class_def)
# Find all the macros (`attr_reader`, `attr_writer`, etc.) in the class body
# and turn them into `Macro` objects so that they can be processed.
return {} if !class_def || class_def.def_type?
send_nodes =
if class_def.send_type?
[class_def]
else
class_def.each_child_node(:send)
end
send_nodes.each_with_object([]) do |node, macros|
macros << Macro.new(node) if Macro.macro?(node)
end.group_by(&:visibility)
end
def find_bisection(macros)
# Find which attributes are defined in both readers and writers so that they
# can be replaced with accessors.
readers, writers = macros.partition(&:reader?)
readers.flat_map(&:attr_names) & writers.flat_map(&:attr_names)
end
def register_offense(attr)
add_offense(attr, message: format(MSG, name: attr.source))
end
def correct_reader(corrector, macro, node, range)
attr_accessor = "attr_accessor #{macro.bisected_names.join(', ')}\n"
if macro.all_bisected?
corrector.replace(range, "#{indent(node)}#{attr_accessor}")
else
correction = "#{indent(node)}attr_reader #{macro.rest.join(', ')}"
corrector.insert_before(node, attr_accessor)
corrector.replace(node, correction)
end
end
def correct_writer(corrector, macro, node, range)
if macro.all_bisected?
corrector.remove(range)
else
correction = "attr_writer #{macro.rest.join(', ')}"
corrector.replace(node, correction)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/empty_method.rb | lib/rubocop/cop/style/empty_method.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the formatting of empty method definitions.
# By default it enforces empty method definitions to go on a single
# line (compact style), but it can be configured to enforce the `end`
# to go on its own line (expanded style).
#
# NOTE: A method definition is not considered empty if it contains
# comments.
#
# NOTE: Autocorrection will not be applied for the `compact` style
# if the resulting code is longer than the `Max` configuration for
# `Layout/LineLength`, but an offense will still be registered.
#
# @example EnforcedStyle: compact (default)
# # bad
# def foo(bar)
# end
#
# def self.foo(bar)
# end
#
# # good
# def foo(bar); end
#
# def foo(bar)
# # baz
# end
#
# def self.foo(bar); end
#
# @example EnforcedStyle: expanded
# # bad
# def foo(bar); end
#
# def self.foo(bar); end
#
# # good
# def foo(bar)
# end
#
# def self.foo(bar)
# end
class EmptyMethod < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG_COMPACT = 'Put empty method definitions on a single line.'
MSG_EXPANDED = 'Put the `end` of empty method definitions on the next line.'
def on_def(node)
return if node.body || processed_source.contains_comment?(node.source_range)
return if correct_style?(node)
add_offense(node) do |corrector|
correction = corrected(node)
next if compact_style? && max_line_length && correction.size > max_line_length
corrector.replace(node, correction)
end
end
alias on_defs on_def
private
def message(_range)
compact_style? ? MSG_COMPACT : MSG_EXPANDED
end
def correct_style?(node)
(compact_style? && compact?(node)) || (expanded_style? && expanded?(node))
end
def corrected(node)
scope = node.receiver ? "#{node.receiver.source}." : ''
arguments = if node.arguments?
args = node.arguments.map(&:source).join(', ')
parentheses?(node.arguments) ? "(#{args})" : " #{args}"
end
signature = [scope, node.method_name, arguments].join
["def #{signature}", 'end'].join(joint(node))
end
def joint(node)
indent = ' ' * node.loc.column
compact_style? ? '; ' : "\n#{indent}"
end
def compact?(node)
node.single_line?
end
def expanded?(node)
node.multiline?
end
def compact_style?
style == :compact
end
def expanded_style?
style == :expanded
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/send_with_literal_method_name.rb | lib/rubocop/cop/style/send_with_literal_method_name.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Detects the use of the `public_send` method with a literal method name argument.
# Since the `send` method can be used to call private methods, by default,
# only the `public_send` method is detected.
#
# NOTE: Writer methods with names ending in `=` are always permitted because their
# behavior differs as follows:
#
# [source,ruby]
# ----
# def foo=(foo)
# @foo = foo
# 42
# end
#
# self.foo = 1 # => 1
# send(:foo=, 1) # => 42
# ----
#
# @safety
# This cop is not safe because it can incorrectly detect based on the receiver.
# Additionally, when `AllowSend` is set to `true`, it cannot determine whether
# the `send` method being detected is calling a private method.
#
# @example
# # bad
# obj.public_send(:method_name)
# obj.public_send('method_name')
#
# # good
# obj.method_name
#
# @example AllowSend: true (default)
# # good
# obj.send(:method_name)
# obj.send('method_name')
# obj.__send__(:method_name)
# obj.__send__('method_name')
#
# @example AllowSend: false
# # bad
# obj.send(:method_name)
# obj.send('method_name')
# obj.__send__(:method_name)
# obj.__send__('method_name')
#
# # good
# obj.method_name
#
class SendWithLiteralMethodName < Base
extend AutoCorrector
MSG = 'Use `%<method_name>s` method call directly instead.'
RESTRICT_ON_SEND = %i[public_send send __send__].freeze
STATIC_METHOD_NAME_NODE_TYPES = %i[sym str].freeze
METHOD_NAME_PATTERN = /\A[a-zA-Z_][a-zA-Z0-9_]*[!?]?\z/.freeze
RESERVED_WORDS = %i[
BEGIN END alias and begin break case class def defined? do else elsif end ensure
false for if in module next nil not or redo rescue retry return self super then true
undef unless until when while yield
].freeze
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def on_send(node)
return if allow_send? && !node.method?(:public_send)
return unless (first_argument = node.first_argument)
return unless first_argument.type?(*STATIC_METHOD_NAME_NODE_TYPES)
offense_range = offense_range(node)
method_name = first_argument.value
return if !METHOD_NAME_PATTERN.match?(method_name) || RESERVED_WORDS.include?(method_name)
add_offense(offense_range, message: format(MSG, method_name: method_name)) do |corrector|
if node.arguments.one?
corrector.replace(offense_range, method_name)
else
corrector.replace(node.loc.selector, method_name)
corrector.remove(removal_argument_range(first_argument, node.arguments[1]))
end
end
end
alias on_csend on_send
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
private
def allow_send?
!!cop_config['AllowSend']
end
def offense_range(node)
node.loc.selector.join(node.source_range.end)
end
def removal_argument_range(first_argument, second_argument)
first_argument.source_range.begin.join(second_argument.source_range.begin)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/class_methods.rb | lib/rubocop/cop/style/class_methods.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of the class/module name instead of
# self, when defining class/module methods.
#
# @example
# # bad
# class SomeClass
# def SomeClass.class_method
# # ...
# end
# end
#
# # good
# class SomeClass
# def self.class_method
# # ...
# end
# end
class ClassMethods < Base
extend AutoCorrector
MSG = 'Use `self.%<method>s` instead of `%<class>s.%<method>s`.'
def on_class(node)
return unless node.body
if node.body.defs_type?
check_defs(node.identifier, node.body)
elsif node.body.begin_type?
node.body.each_child_node(:defs) { |def_node| check_defs(node.identifier, def_node) }
end
end
alias on_module on_class
private
def check_defs(name, node)
# check if the class/module name matches the definee for the defs node
return unless name == node.receiver
message = format(MSG, method: node.method_name, class: name.source)
add_offense(node.receiver.loc.name, message: message) do |corrector|
corrector.replace(node.receiver, 'self')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/double_negation.rb | lib/rubocop/cop/style/double_negation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of double negation (`!!`) to convert something to a boolean value.
#
# When using `EnforcedStyle: allowed_in_returns`, allow double negation in contexts
# that use boolean as a return value. When using `EnforcedStyle: forbidden`, double negation
# should be forbidden always.
#
# NOTE: when `something` is a boolean value
# `!!something` and `!something.nil?` are not the same thing.
# As you're unlikely to write code that can accept values of any type
# this is rarely a problem in practice.
#
# @safety
# Autocorrection is unsafe when the value is `false`, because the result
# of the expression will change.
#
# [source,ruby]
# ----
# !!false #=> false
# !false.nil? #=> true
# ----
#
# @example
# # bad
# !!something
#
# # good
# !something.nil?
#
# @example EnforcedStyle: allowed_in_returns (default)
# # good
# def foo?
# !!return_value
# end
#
# define_method :foo? do
# !!return_value
# end
#
# define_singleton_method :foo? do
# !!return_value
# end
#
# @example EnforcedStyle: forbidden
# # bad
# def foo?
# !!return_value
# end
#
# define_method :foo? do
# !!return_value
# end
#
# define_singleton_method :foo? do
# !!return_value
# end
class DoubleNegation < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Avoid the use of double negation (`!!`).'
RESTRICT_ON_SEND = %i[!].freeze
# @!method double_negative?(node)
def_node_matcher :double_negative?, '(send (send _ :!) :!)'
def on_send(node)
return unless double_negative?(node) && node.prefix_bang?
return if style == :allowed_in_returns && allowed_in_returns?(node)
location = node.loc.selector
add_offense(location) do |corrector|
corrector.remove(location)
corrector.insert_after(node, '.nil?')
end
end
private
def allowed_in_returns?(node)
node.parent&.return_type? || end_of_method_definition?(node)
end
def end_of_method_definition?(node)
return false unless (def_node = find_def_node_from_ascendant(node))
conditional_node = find_conditional_node_from_ascendant(node)
last_child = find_last_child(def_node.send_type? ? def_node : def_node.body)
if conditional_node
double_negative_condition_return_value?(node, last_child, conditional_node)
elsif last_child.type?(:pair, :hash) || last_child.parent.array_type?
false
else
last_child.first_line <= node.first_line
end
end
def find_def_node_from_ascendant(node)
return unless (parent = node.parent)
return parent if parent.any_def_type?
return node.parent.child_nodes.first if define_method?(parent)
find_def_node_from_ascendant(node.parent)
end
def define_method?(node)
return false unless node.any_block_type?
child = node.child_nodes.first
return false unless child.send_type?
child.method?(:define_method) || child.method?(:define_singleton_method)
end
def find_conditional_node_from_ascendant(node)
return unless (parent = node.parent)
return parent if parent.conditional?
find_conditional_node_from_ascendant(parent)
end
def find_last_child(node)
case node.type
when :rescue
find_last_child(node.body)
when :ensure
find_last_child(node.child_nodes.first)
else
node.child_nodes.last
end
end
def double_negative_condition_return_value?(node, last_child, conditional_node)
parent = find_parent_not_enumerable(node)
if parent.begin_type?
node.loc.line == parent.loc.last_line
else
last_child.last_line <= conditional_node.last_line
end
end
def find_parent_not_enumerable(node)
return unless (parent = node.parent)
if parent.type?(:pair, :hash, :array)
find_parent_not_enumerable(parent)
else
parent
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/regexp_literal.rb | lib/rubocop/cop/style/regexp_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces using `//` or `%r` around regular expressions.
#
# NOTE: The following `%r` cases using a regexp starts with a blank or `=`
# as a method argument allowed to prevent syntax errors.
#
# [source,ruby]
# ----
# do_something %r{ regexp} # `do_something / regexp/` is an invalid syntax.
# do_something %r{=regexp} # `do_something /=regexp/` is an invalid syntax.
# ----
#
# @example EnforcedStyle: slashes (default)
# # bad
# snake_case = %r{^[\dA-Z_]+$}
#
# # bad
# regex = %r{
# foo
# (bar)
# (baz)
# }x
#
# # good
# snake_case = /^[\dA-Z_]+$/
#
# # good
# regex = /
# foo
# (bar)
# (baz)
# /x
#
# @example EnforcedStyle: percent_r
# # bad
# snake_case = /^[\dA-Z_]+$/
#
# # bad
# regex = /
# foo
# (bar)
# (baz)
# /x
#
# # good
# snake_case = %r{^[\dA-Z_]+$}
#
# # good
# regex = %r{
# foo
# (bar)
# (baz)
# }x
#
# @example EnforcedStyle: mixed
# # bad
# snake_case = %r{^[\dA-Z_]+$}
#
# # bad
# regex = /
# foo
# (bar)
# (baz)
# /x
#
# # good
# snake_case = /^[\dA-Z_]+$/
#
# # good
# regex = %r{
# foo
# (bar)
# (baz)
# }x
#
# @example AllowInnerSlashes: false (default)
# # If `false`, the cop will always recommend using `%r` if one or more
# # slashes are found in the regexp string.
#
# # bad
# x =~ /home\//
#
# # good
# x =~ %r{home/}
#
# @example AllowInnerSlashes: true
# # good
# x =~ /home\//
class RegexpLiteral < Base
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG_USE_SLASHES = 'Use `//` around regular expression.'
MSG_USE_PERCENT_R = 'Use `%r` around regular expression.'
def on_regexp(node)
message = if slash_literal?(node)
MSG_USE_PERCENT_R unless allowed_slash_literal?(node)
else
MSG_USE_SLASHES unless allowed_percent_r_literal?(node)
end
return unless message
add_offense(node, message: message) do |corrector|
correct_delimiters(node, corrector)
correct_inner_slashes(node, corrector)
end
end
private
def allowed_slash_literal?(node)
(style == :slashes && !contains_disallowed_slash?(node)) || allowed_mixed_slash?(node)
end
def allowed_mixed_slash?(node)
style == :mixed && node.single_line? && !contains_disallowed_slash?(node)
end
def allowed_percent_r_literal?(node)
(style == :slashes && contains_disallowed_slash?(node)) ||
style == :percent_r ||
allowed_mixed_percent_r?(node) || allowed_omit_parentheses_with_percent_r_literal?(node)
end
def allowed_mixed_percent_r?(node)
(style == :mixed && node.multiline?) || contains_disallowed_slash?(node)
end
def contains_disallowed_slash?(node)
!allow_inner_slashes? && contains_slash?(node)
end
def contains_slash?(node)
node_body(node).include?('/')
end
def allow_inner_slashes?
cop_config['AllowInnerSlashes']
end
def node_body(node, include_begin_nodes: false)
types = include_begin_nodes ? %i[str begin] : %i[str]
node.each_child_node(*types).map(&:source).join
end
def slash_literal?(node)
node.loc.begin.source == '/'
end
def preferred_delimiters
config.for_cop('Style/PercentLiteralDelimiters')['PreferredDelimiters']['%r'].chars
end
def allowed_omit_parentheses_with_percent_r_literal?(node)
return false unless node.parent&.call_type?
return true if node.content.start_with?(' ', '=')
enforced_style = config.for_cop('Style/MethodCallWithArgsParentheses')['EnforcedStyle']
enforced_style == 'omit_parentheses'
end
def correct_delimiters(node, corrector)
replacement = calculate_replacement(node)
corrector.replace(node.loc.begin, replacement.first)
corrector.replace(node.loc.end, replacement.last)
end
def correct_inner_slashes(node, corrector)
regexp_begin = node.loc.begin.end_pos
inner_slash_indices(node).each do |index|
start = regexp_begin + index
corrector.replace(
range_between(
start,
start + inner_slash_before_correction(node).length
),
inner_slash_after_correction(node)
)
end
end
def inner_slash_indices(node)
text = node_body(node, include_begin_nodes: true)
pattern = inner_slash_before_correction(node)
index = -1
indices = []
while (index = text.index(pattern, index + 1))
indices << index
end
indices
end
def inner_slash_before_correction(node)
inner_slash_for(node.loc.begin.source)
end
def inner_slash_after_correction(node)
inner_slash_for(calculate_replacement(node).first)
end
def inner_slash_for(opening_delimiter)
if ['/', '%r/'].include?(opening_delimiter)
'\/'
else
'/'
end
end
def calculate_replacement(node)
if slash_literal?(node)
['%r', ''].zip(preferred_delimiters).map(&:join)
else
%w[/ /]
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/multiple_comparison.rb | lib/rubocop/cop/style/multiple_comparison.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks against comparing a variable with multiple items, where
# `Array#include?`, `Set#include?` or a `case` could be used instead
# to avoid code repetition.
# It accepts comparisons of multiple method calls to avoid unnecessary method calls
# by default. It can be configured by `AllowMethodComparison` option.
#
# @example
# # bad
# a = 'a'
# foo if a == 'a' || a == 'b' || a == 'c'
#
# # good
# a = 'a'
# foo if ['a', 'b', 'c'].include?(a)
#
# VALUES = Set['a', 'b', 'c'].freeze
# # elsewhere...
# foo if VALUES.include?(a)
#
# case foo
# when 'a', 'b', 'c' then foo
# # ...
# end
#
# # accepted (but consider `case` as above)
# foo if a == b.lightweight || a == b.heavyweight
#
# @example AllowMethodComparison: true (default)
# # good
# foo if a == b.lightweight || a == b.heavyweight
#
# @example AllowMethodComparison: false
# # bad
# foo if a == b.lightweight || a == b.heavyweight
#
# # good
# foo if [b.lightweight, b.heavyweight].include?(a)
#
# @example ComparisonsThreshold: 2 (default)
# # bad
# foo if a == 'a' || a == 'b'
#
# @example ComparisonsThreshold: 3
# # good
# foo if a == 'a' || a == 'b'
#
class MultipleComparison < Base
extend AutoCorrector
MSG = 'Avoid comparing a variable with multiple items ' \
'in a conditional, use `Array#include?` instead.'
# @!method simple_double_comparison?(node)
def_node_matcher :simple_double_comparison?, <<~PATTERN
(send lvar :== lvar)
PATTERN
# @!method simple_comparison_lhs(node)
def_node_matcher :simple_comparison_lhs, <<~PATTERN
(send ${lvar call} :== $_)
PATTERN
# @!method simple_comparison_rhs(node)
def_node_matcher :simple_comparison_rhs, <<~PATTERN
(send $_ :== ${lvar call})
PATTERN
# rubocop:disable Metrics/AbcSize
def on_or(node)
root_of_or_node = root_of_or_node(node)
return unless node == root_of_or_node
return unless nested_comparison?(node)
return unless (variable, values = find_offending_var(node))
return if values.size < comparisons_threshold
range = offense_range(values)
add_offense(range) do |corrector|
elements = values.map(&:source).join(', ')
argument = variable.lvar_type? ? variable_name(variable) : variable.source
prefer_method = "[#{elements}].include?(#{argument})"
corrector.replace(range, prefer_method)
end
end
# rubocop:enable Metrics/AbcSize
private
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def find_offending_var(node, variables = Set.new, values = [])
if node.or_type?
find_offending_var(node.lhs, variables, values)
find_offending_var(node.rhs, variables, values)
elsif simple_double_comparison?(node)
return
elsif (var, obj = simple_comparison(node))
return if allow_method_comparison? && obj.call_type?
variables << var
return if variables.size > 1
values << obj
end
[variables.first, values] if variables.any?
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def offense_range(values)
values.first.parent.source_range.begin.join(values.last.parent.source_range.end)
end
def variable_name(node)
node.children[0]
end
def nested_comparison?(node)
if node.or_type?
node.node_parts.all? { |node_part| comparison? node_part }
else
false
end
end
def comparison?(node)
!!simple_comparison(node) || nested_comparison?(node)
end
def simple_comparison(node)
if (var, obj = simple_comparison_lhs(node)) || (obj, var = simple_comparison_rhs(node))
return if var.call_type? && !allow_method_comparison?
[var, obj]
end
end
def root_of_or_node(or_node)
return or_node unless or_node.parent
if or_node.parent.or_type?
root_of_or_node(or_node.parent)
else
or_node
end
end
def allow_method_comparison?
cop_config.fetch('AllowMethodComparison', true)
end
def comparisons_threshold
cop_config.fetch('ComparisonsThreshold', 2)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/array_first_last.rb | lib/rubocop/cop/style/array_first_last.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Identifies usages of `arr[0]` and `arr[-1]` and suggests to change
# them to use `arr.first` and `arr.last` instead.
#
# The cop is disabled by default due to safety concerns.
#
# @safety
# This cop is unsafe because `[0]` or `[-1]` can be called on a Hash,
# which returns a value for `0` or `-1` key, but changing these to use
# `.first` or `.last` will return first/last tuple instead. Also, String
# does not implement `first`/`last` methods.
#
# @example
# # bad
# arr[0]
# arr[-1]
#
# # good
# arr.first
# arr.last
# arr[0] = 2
# arr[0][-2]
#
class ArrayFirstLast < Base
extend AutoCorrector
MSG = 'Use `%<preferred>s`.'
RESTRICT_ON_SEND = %i[[]].freeze
# rubocop:disable Metrics/AbcSize
def on_send(node)
return unless node.arguments.size == 1 && node.first_argument.int_type?
value = node.first_argument.value
return unless [0, -1].include?(value)
node = innermost_braces_node(node)
return if node.parent && brace_method?(node.parent)
preferred = (value.zero? ? 'first' : 'last')
offense_range = find_offense_range(node)
add_offense(offense_range, message: format(MSG, preferred: preferred)) do |corrector|
corrector.replace(offense_range, preferred_value(node, preferred))
end
end
# rubocop:enable Metrics/AbcSize
alias on_csend on_send
private
def preferred_value(node, value)
value = ".#{value}" unless node.loc.dot
value
end
def find_offense_range(node)
if node.loc.dot
node.loc.selector.join(node.source_range.end)
else
node.loc.selector
end
end
def innermost_braces_node(node)
node = node.receiver while node.receiver.send_type? && node.receiver.method?(:[])
node
end
def brace_method?(node)
node.send_type? && (node.method?(:[]) || node.method?(:[]=))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/hash_syntax.rb | lib/rubocop/cop/style/hash_syntax.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks hash literal syntax.
#
# It can enforce either the use of the class hash rocket syntax or
# the use of the newer Ruby 1.9 syntax (when applicable).
#
# A separate offense is registered for each problematic pair.
#
# The supported styles are:
#
# * ruby19 - forces use of the 1.9 syntax (e.g. `{a: 1}`) when hashes have
# all symbols for keys
# * hash_rockets - forces use of hash rockets for all hashes
# * no_mixed_keys - simply checks for hashes with mixed syntaxes
# * ruby19_no_mixed_keys - forces use of ruby 1.9 syntax and forbids mixed
# syntax hashes
#
# This cop has `EnforcedShorthandSyntax` option.
# It can enforce either the use of the explicit hash value syntax or
# the use of Ruby 3.1's hash value shorthand syntax.
#
# The supported styles are:
#
# * always - forces use of the 3.1 syntax (e.g. {foo:})
# * never - forces use of explicit hash literal value
# * either - accepts both shorthand and explicit use of hash literal value
# * consistent - forces use of the 3.1 syntax only if all values can be omitted in the hash
# * either_consistent - accepts both shorthand and explicit use of hash literal value,
# but they must be consistent
#
# @example EnforcedStyle: ruby19 (default)
# # bad
# {:a => 2}
# {b: 1, :c => 2}
#
# # good
# {a: 2, b: 1}
# {:c => 2, 'd' => 2} # acceptable since 'd' isn't a symbol
# {d: 1, 'e' => 2} # technically not forbidden
#
# @example EnforcedStyle: hash_rockets
# # bad
# {a: 1, b: 2}
# {c: 1, 'd' => 5}
#
# # good
# {:a => 1, :b => 2}
#
# @example EnforcedStyle: no_mixed_keys
# # bad
# {:a => 1, b: 2}
# {c: 1, 'd' => 2}
#
# # good
# {:a => 1, :b => 2}
# {c: 1, d: 2}
#
# @example EnforcedStyle: ruby19_no_mixed_keys
# # bad
# {:a => 1, :b => 2}
# {c: 2, 'd' => 3} # should just use hash rockets
#
# # good
# {a: 1, b: 2}
# {:c => 3, 'd' => 4}
#
# @example EnforcedShorthandSyntax: always
#
# # bad
# {foo: foo, bar: bar}
#
# # good
# {foo:, bar:}
#
# # good - allowed to mix syntaxes
# {foo:, bar: baz}
#
# @example EnforcedShorthandSyntax: never
#
# # bad
# {foo:, bar:}
#
# # good
# {foo: foo, bar: bar}
#
# @example EnforcedShorthandSyntax: either (default)
#
# # good
# {foo: foo, bar: bar}
#
# # good
# {foo: foo, bar:}
#
# # good
# {foo:, bar:}
#
# @example EnforcedShorthandSyntax: consistent
#
# # bad - `foo` and `bar` values can be omitted
# {foo: foo, bar: bar}
#
# # bad - `bar` value can be omitted
# {foo:, bar: bar}
#
# # bad - mixed syntaxes
# {foo:, bar: baz}
#
# # good
# {foo:, bar:}
#
# # good - can't omit `baz`
# {foo: foo, bar: baz}
#
# @example EnforcedShorthandSyntax: either_consistent
#
# # good - `foo` and `bar` values can be omitted, but they are consistent, so it's accepted
# {foo: foo, bar: bar}
#
# # bad - `bar` value can be omitted
# {foo:, bar: bar}
#
# # bad - mixed syntaxes
# {foo:, bar: baz}
#
# # good
# {foo:, bar:}
#
# # good - can't omit `baz`
# {foo: foo, bar: baz}
class HashSyntax < Base
include ConfigurableEnforcedStyle
include HashShorthandSyntax
include RangeHelp
extend AutoCorrector
MSG_19 = 'Use the new Ruby 1.9 hash syntax.'
MSG_NO_MIXED_KEYS = "Don't mix styles in the same hash."
MSG_HASH_ROCKETS = 'Use hash rockets syntax.'
NO_MIXED_KEYS_STYLES = %i[ruby19_no_mixed_keys no_mixed_keys].freeze
def on_hash(node)
pairs = node.pairs
return if pairs.empty?
on_hash_for_mixed_shorthand(node)
if style == :hash_rockets || force_hash_rockets?(pairs)
hash_rockets_check(pairs)
elsif style == :ruby19_no_mixed_keys
ruby19_no_mixed_keys_check(pairs)
elsif style == :no_mixed_keys
no_mixed_keys_check(pairs)
else
ruby19_check(pairs)
end
end
def ruby19_check(pairs)
check(pairs, '=>', MSG_19) if sym_indices?(pairs)
end
def hash_rockets_check(pairs)
check(pairs, ':', MSG_HASH_ROCKETS)
end
def ruby19_no_mixed_keys_check(pairs)
if force_hash_rockets?(pairs)
check(pairs, ':', MSG_HASH_ROCKETS)
elsif sym_indices?(pairs)
check(pairs, '=>', MSG_19)
else
check(pairs, ':', MSG_NO_MIXED_KEYS)
end
end
def no_mixed_keys_check(pairs)
if sym_indices?(pairs)
check(pairs, pairs.first.inverse_delimiter, MSG_NO_MIXED_KEYS)
else
check(pairs, ':', MSG_NO_MIXED_KEYS)
end
end
def alternative_style
case style
when :hash_rockets
:ruby19
when :ruby19, :ruby19_no_mixed_keys
:hash_rockets
end
end
private
def autocorrect(corrector, node)
if style == :hash_rockets || force_hash_rockets?(node.parent.pairs)
autocorrect_hash_rockets(corrector, node)
elsif NO_MIXED_KEYS_STYLES.include?(style)
autocorrect_no_mixed_keys(corrector, node)
else
autocorrect_ruby19(corrector, node)
end
end
def sym_indices?(pairs)
pairs.all? { |p| word_symbol_pair?(p) }
end
def word_symbol_pair?(pair)
return false unless pair.key.any_sym_type?
acceptable_19_syntax_symbol?(pair.key.source)
end
# rubocop:disable Metrics/CyclomaticComplexity
def acceptable_19_syntax_symbol?(sym_name)
sym_name.delete_prefix!(':')
if cop_config['PreferHashRocketsForNonAlnumEndingSymbols'] &&
# Prefer { :production? => false } over { production?: false } and
# similarly for other non-alnum final characters (except quotes,
# to prefer { "x y": 1 } over { :"x y" => 1 }).
!/[\p{Alnum}"']\z/.match?(sym_name)
return false
end
# Most hash keys can be matched against a simple regex.
return true if /\A[_a-z]\w*[?!]?\z/i.match?(sym_name)
return false if target_ruby_version <= 2.1
(sym_name.start_with?("'") && sym_name.end_with?("'")) ||
(sym_name.start_with?('"') && sym_name.end_with?('"'))
end
# rubocop:enable Metrics/CyclomaticComplexity
def check(pairs, delim, msg)
pairs.each do |pair|
if pair.delimiter == delim
location = pair.source_range.begin.join(pair.loc.operator)
add_offense(location, message: msg) do |corrector|
autocorrect(corrector, pair)
opposite_style_detected
end
else
correct_style_detected
end
end
end
def autocorrect_ruby19(corrector, pair_node)
range = range_for_autocorrect_ruby19(pair_node)
space = argument_without_space?(pair_node.parent) ? ' ' : ''
corrector.replace(range, range.source.sub(/^:(.*\S)\s*=>\s*$/, "#{space}\\1: "))
hash_node = pair_node.parent
return unless hash_node.parent&.return_type? && !hash_node.braces?
corrector.wrap(hash_node, '{', '}')
end
def range_for_autocorrect_ruby19(pair_node)
key = pair_node.key.source_range
operator = pair_node.loc.operator
range = key.join(operator)
range_with_surrounding_space(range, side: :right)
end
def argument_without_space?(node)
return false if !node.argument? || !node.parent.loc.selector
node.source_range.begin_pos == node.parent.loc.selector.end_pos
end
def autocorrect_hash_rockets(corrector, pair_node)
op = pair_node.loc.operator
key_with_hash_rocket = ":#{pair_node.key.source}#{pair_node.inverse_delimiter(true)}"
key_with_hash_rocket += pair_node.key.source if pair_node.value_omission?
corrector.replace(pair_node.key, key_with_hash_rocket)
corrector.remove(range_with_surrounding_space(op))
end
def autocorrect_no_mixed_keys(corrector, pair_node)
if pair_node.colon?
autocorrect_hash_rockets(corrector, pair_node)
else
autocorrect_ruby19(corrector, pair_node)
end
end
def force_hash_rockets?(pairs)
cop_config['UseHashRocketsWithSymbolValues'] && pairs.map(&:value).any?(&:sym_type?)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/variable_interpolation.rb | lib/rubocop/cop/style/variable_interpolation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for variable interpolation (like "#@ivar").
#
# @example
# # bad
# "His name is #$name"
# /check #$pattern/
# "Let's go to the #@store"
#
# # good
# "His name is #{$name}"
# /check #{$pattern}/
# "Let's go to the #{@store}"
class VariableInterpolation < Base
include Interpolation
extend AutoCorrector
MSG = 'Replace interpolated variable `%<variable>s` with expression `#{%<variable>s}`.'
def on_node_with_interpolations(node)
var_nodes(node.children).each do |var_node|
add_offense(var_node) do |corrector|
corrector.replace(var_node, "{#{var_node.source}}")
end
end
end
private
def message(range)
format(MSG, variable: range.source)
end
def var_nodes(nodes)
nodes.select { |n| n.variable? || n.reference? }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/line_end_concatenation.rb | lib/rubocop/cop/style/line_end_concatenation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for string literal concatenation at
# the end of a line.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the
# receiver is a string, in which case replacing `<<` with `\`
# would result in a syntax error.
#
# For example, this would be a false positive:
# [source,ruby]
# ----
# array << 'foo' <<
# 'bar' <<
# 'baz'
# ----
#
# @example
#
# # bad
# some_str = 'ala' +
# 'bala'
#
# some_str = 'ala' <<
# 'bala'
#
# # good
# some_str = 'ala' \
# 'bala'
#
class LineEndConcatenation < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `\\` instead of `%<operator>s` to concatenate multiline strings.'
CONCAT_TOKEN_TYPES = %i[tPLUS tLSHFT].freeze
SIMPLE_STRING_TOKEN_TYPE = :tSTRING
COMPLEX_STRING_BEGIN_TOKEN = :tSTRING_BEG
COMPLEX_STRING_END_TOKEN = :tSTRING_END
HIGH_PRECEDENCE_OP_TOKEN_TYPES = %i[tSTAR2 tPERCENT tDOT tLBRACK2].freeze
QUOTE_DELIMITERS = %w[' "].freeze
def self.autocorrect_incompatible_with
[Style::RedundantInterpolation]
end
def on_new_investigation
processed_source.tokens.each_index { |index| check_token_set(index) }
end
private
def check_token_set(index)
tokens = processed_source.tokens
predecessor = tokens[index]
operator = tokens[index + 1]
successor = tokens[index + 2]
return unless eligible_token_set?(predecessor, operator, successor)
return if same_line?(operator, successor)
next_successor = token_after_last_string(successor, index)
return unless eligible_next_successor?(next_successor)
register_offense(operator)
end
def register_offense(operator)
message = format(MSG, operator: operator.text)
add_offense(operator.pos, message: message) do |corrector|
autocorrect(corrector, operator.pos)
end
end
def autocorrect(corrector, operator_range)
# Include any trailing whitespace so we don't create a syntax error.
operator_range = range_with_surrounding_space(operator_range,
side: :right,
newlines: false)
one_more_char = operator_range.resize(operator_range.size + 1)
# Don't create a double backslash at the end of the line, in case
# there already was a backslash after the concatenation operator.
operator_range = one_more_char if one_more_char.source.end_with?('\\')
corrector.replace(operator_range, '\\')
end
def eligible_token_set?(predecessor, operator, successor)
eligible_successor?(successor) &&
eligible_operator?(operator) &&
eligible_predecessor?(predecessor)
end
def eligible_successor?(successor)
successor && standard_string_literal?(successor)
end
def eligible_operator?(operator)
CONCAT_TOKEN_TYPES.include?(operator.type)
end
def eligible_next_successor?(next_successor)
!(next_successor && HIGH_PRECEDENCE_OP_TOKEN_TYPES.include?(next_successor.type))
end
def eligible_predecessor?(predecessor)
standard_string_literal?(predecessor)
end
def token_after_last_string(successor, base_index)
index = base_index + 3
if successor.type == COMPLEX_STRING_BEGIN_TOKEN
ends_to_find = 1
while ends_to_find.positive?
case processed_source.tokens[index].type
when COMPLEX_STRING_BEGIN_TOKEN then ends_to_find += 1
when COMPLEX_STRING_END_TOKEN then ends_to_find -= 1
end
index += 1
end
end
processed_source.tokens[index]
end
def standard_string_literal?(token)
case token.type
when SIMPLE_STRING_TOKEN_TYPE
true
when COMPLEX_STRING_BEGIN_TOKEN, COMPLEX_STRING_END_TOKEN
QUOTE_DELIMITERS.include?(token.text)
else
false
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_initialize.rb | lib/rubocop/cop/style/redundant_initialize.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for `initialize` methods that are redundant.
#
# An initializer is redundant if it does not do anything, or if it only
# calls `super` with the same arguments given to it. If the initializer takes
# an argument that accepts multiple values (`restarg`, `kwrestarg`, etc.) it
# will not register an offense, because it allows the initializer to take a different
# number of arguments as its superclass potentially does.
#
# NOTE: If an initializer takes any arguments and has an empty body, RuboCop
# assumes it to *not* be redundant. This is to prevent potential `ArgumentError`.
#
# NOTE: If an initializer argument has a default value, RuboCop assumes it
# to *not* be redundant.
#
# NOTE: Empty initializers are registered as offenses, but it is possible
# to purposely create an empty `initialize` method to override a superclass's
# initializer.
#
# @safety
# This cop is unsafe because removing an empty initializer may alter
# the behavior of the code, particularly if the superclass initializer
# raises an exception. In such cases, the empty initializer may act as
# a safeguard to prevent unintended errors from propagating.
#
# @example
# # bad
# def initialize
# end
#
# # bad
# def initialize
# super
# end
#
# # bad
# def initialize(a, b)
# super
# end
#
# # bad
# def initialize(a, b)
# super(a, b)
# end
#
# # good
# def initialize
# do_something
# end
#
# # good
# def initialize
# do_something
# super
# end
#
# # good (different number of parameters)
# def initialize(a, b)
# super(a)
# end
#
# # good (default value)
# def initialize(a, b = 5)
# super
# end
#
# # good (default value)
# def initialize(a, b: 5)
# super
# end
#
# # good (changes the parameter requirements)
# def initialize(_)
# end
#
# # good (changes the parameter requirements)
# def initialize(*)
# end
#
# # good (changes the parameter requirements)
# def initialize(**)
# end
#
# # good (changes the parameter requirements)
# def initialize(...)
# end
#
# @example AllowComments: true (default)
#
# # good
# def initialize
# # Overriding to negate superclass `initialize` method.
# end
#
# @example AllowComments: false
#
# # bad
# def initialize
# # Overriding to negate superclass `initialize` method.
# end
#
class RedundantInitialize < Base
include CommentsHelp
include RangeHelp
extend AutoCorrector
MSG = 'Remove unnecessary `initialize` method.'
MSG_EMPTY = 'Remove unnecessary empty `initialize` method.'
# @!method initialize_forwards?(node)
def_node_matcher :initialize_forwards?, <<~PATTERN
(def _ (args $arg*) $({super zsuper} ...))
PATTERN
def on_def(node)
return if acceptable?(node)
if node.body.nil?
register_offense(node, MSG_EMPTY) if node.arguments.empty?
else
return if node.body.begin_type?
if (args, super_node = initialize_forwards?(node))
return unless same_args?(super_node, args)
register_offense(node, MSG)
end
end
end
private
def register_offense(node, message)
add_offense(node, message: message) do |corrector|
corrector.remove(range_by_whole_lines(node.source_range, include_final_newline: true))
end
end
def acceptable?(node)
!node.method?(:initialize) || forwards?(node) || allow_comments?(node)
end
def forwards?(node)
node.arguments.each_child_node(:restarg, :kwrestarg, :forward_args, :forward_arg).any?
end
def allow_comments?(node)
return false unless cop_config['AllowComments']
contains_comments?(node) && !comments_contain_disables?(node, name)
end
def same_args?(super_node, args)
return true if super_node.zsuper_type?
args.map(&:name) == super_node.arguments.map { |a| a.children[0] }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/negated_if_else_condition.rb | lib/rubocop/cop/style/negated_if_else_condition.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of `if-else` and ternary operators with a negated condition
# which can be simplified by inverting condition and swapping branches.
#
# @example
# # bad
# if !x
# do_something
# else
# do_something_else
# end
#
# # good
# if x
# do_something_else
# else
# do_something
# end
#
# # bad
# !x ? do_something : do_something_else
#
# # good
# x ? do_something_else : do_something
#
class NegatedIfElseCondition < Base
include RangeHelp
extend AutoCorrector
MSG = 'Invert the negated condition and swap the %<type>s branches.'
NEGATED_EQUALITY_METHODS = %i[!= !~].freeze
# @!method double_negation?(node)
def_node_matcher :double_negation?, '(send (send _ :!) :!)'
def self.autocorrect_incompatible_with
[Style::InverseMethods, Style::Not]
end
def on_new_investigation
@corrected_nodes = nil
end
# rubocop:disable Metrics/AbcSize,Metrics/CyclomaticComplexity
def on_if(node)
return unless if_else?(node)
return unless (condition = unwrap_begin_nodes(node.condition))
return if double_negation?(condition) || !negated_condition?(condition)
return unless condition.arguments.size < 2
message = message(node)
add_offense(node, message: message) do |corrector|
unless corrected_ancestor?(node)
correct_negated_condition(corrector, condition)
swap_branches(corrector, node)
@corrected_nodes ||= Set.new.compare_by_identity
@corrected_nodes.add(node)
end
end
end
# rubocop:enable Metrics/AbcSize,Metrics/CyclomaticComplexity
private
def if_else?(node)
else_branch = node.else_branch
!node.elsif? && else_branch && (!else_branch.if_type? || !else_branch.elsif?)
end
def unwrap_begin_nodes(node)
node = node.children.first while node&.type?(:begin, :kwbegin)
node
end
def negated_condition?(node)
node.send_type? &&
(node.negation_method? || NEGATED_EQUALITY_METHODS.include?(node.method_name))
end
def message(node)
type = node.ternary? ? 'ternary' : 'if-else'
format(MSG, type: type)
end
def corrected_ancestor?(node)
node.each_ancestor(:if).any? { |ancestor| @corrected_nodes&.include?(ancestor) }
end
def correct_negated_condition(corrector, node)
replacement =
if node.negation_method?
node.receiver.source
else
inverted_method = node.method_name.to_s.sub('!', '=')
"#{node.receiver.source} #{inverted_method} #{node.first_argument.source}"
end
corrector.replace(node, replacement)
end
def swap_branches(corrector, node)
if node.if_branch.nil?
corrector.remove(range_by_whole_lines(node.loc.else, include_final_newline: true))
else
corrector.swap(if_range(node), else_range(node))
end
end
# Collect the entire if branch, including whitespace and comments
def if_range(node)
if node.ternary?
node.if_branch
else
range_between(node.condition.source_range.end_pos, node.loc.else.begin_pos)
end
end
# Collect the entire else branch, including whitespace and comments
def else_range(node)
if node.ternary?
node.else_branch
else
range_between(node.loc.else.end_pos, node.loc.end.begin_pos)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/if_with_boolean_literal_branches.rb | lib/rubocop/cop/style/if_with_boolean_literal_branches.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant `if` with boolean literal branches.
# It checks only conditions to return boolean value (`true` or `false`) for safe detection.
# The conditions to be checked are comparison methods, predicate methods, and
# double negation (!!).
# `nonzero?` method is allowed by default.
# These are customizable with `AllowedMethods` option.
#
# This cop targets only ``if``s with a single `elsif` or `else` branch. The following
# code will be allowed, because it has two `elsif` branches:
#
# [source,ruby]
# ----
# if foo
# true
# elsif bar > baz
# true
# elsif qux > quux # Single `elsif` is warned, but two or more `elsif`s are not.
# true
# else
# false
# end
# ----
#
# @safety
# Autocorrection is unsafe because there is no guarantee that all predicate methods
# will return a boolean value. Those methods can be allowed with `AllowedMethods` config.
#
# @example
# # bad
# if foo == bar
# true
# else
# false
# end
#
# # bad
# foo == bar ? true : false
#
# # good
# foo == bar
#
# # bad
# if foo.do_something?
# true
# else
# false
# end
#
# # good (but potentially an unsafe correction)
# foo.do_something?
#
# @example AllowedMethods: ['nonzero?'] (default)
# # good
# num.nonzero? ? true : false
#
class IfWithBooleanLiteralBranches < Base
include AllowedMethods
extend AutoCorrector
MSG = 'Remove redundant %<keyword>s with boolean literal branches.'
MSG_FOR_ELSIF = 'Use `else` instead of redundant `elsif` with boolean literal branches.'
# @!method if_with_boolean_literal_branches?(node)
def_node_matcher :if_with_boolean_literal_branches?, <<~PATTERN
(if #return_boolean_value? <true false>)
PATTERN
# @!method double_negative?(node)
def_node_matcher :double_negative?, '(send (send _ :!) :!)'
def on_if(node)
return if !if_with_boolean_literal_branches?(node) || multiple_elsif?(node)
condition = node.condition
range, keyword = offense_range_with_keyword(node, condition)
add_offense(range, message: message(node, keyword)) do |corrector|
replacement = replacement_condition(node, condition)
if node.elsif?
corrector.insert_before(node, "else\n")
corrector.replace(node, "#{indent(node.if_branch)}#{replacement}")
else
corrector.replace(node, replacement)
end
end
end
private
def multiple_elsif?(node)
return false unless (parent = node.parent)
parent.if_type? && parent.elsif?
end
def offense_range_with_keyword(node, condition)
if node.ternary?
range = condition.source_range.end.join(node.source_range.end)
[range, 'ternary operator']
else
keyword = node.loc.keyword
[keyword, "`#{keyword.source}`"]
end
end
def message(node, keyword)
if node.elsif?
MSG_FOR_ELSIF
else
format(MSG, keyword: keyword)
end
end
def return_boolean_value?(condition)
return false unless condition
if condition.begin_type?
return_boolean_value?(condition.children.first)
elsif condition.or_type?
return_boolean_value?(condition.lhs) && return_boolean_value?(condition.rhs)
elsif condition.and_type?
return_boolean_value?(condition.rhs)
else
assume_boolean_value?(condition)
end
end
def assume_boolean_value?(condition)
return false unless condition.send_type?
return false if allowed_method?(condition.method_name)
condition.comparison_method? || condition.predicate_method? || double_negative?(condition)
end
def replacement_condition(node, condition)
bang = '!' if opposite_condition?(node)
if bang && require_parentheses?(condition)
"#{bang}(#{condition.source})"
else
"#{bang}#{condition.source}"
end
end
def opposite_condition?(node)
(!node.unless? && node.if_branch.false_type?) ||
(node.unless? && node.if_branch.true_type?)
end
def require_parentheses?(condition)
condition.operator_keyword? || (condition.send_type? && condition.comparison_method?)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/trailing_body_on_class.rb | lib/rubocop/cop/style/trailing_body_on_class.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for trailing code after the class definition.
#
# @example
# # bad
# class Foo; def foo; end
# end
#
# # good
# class Foo
# def foo; end
# end
#
class TrailingBodyOnClass < Base
include Alignment
include TrailingBody
extend AutoCorrector
MSG = 'Place the first line of class body on its own line.'
def on_class(node)
return unless trailing_body?(node)
add_offense(first_part_of(node.to_a.last)) do |corrector|
LineBreakCorrector.correct_trailing_body(
configured_width: configured_indentation_width,
corrector: corrector,
node: node,
processed_source: processed_source
)
end
end
alias on_sclass on_class
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/method_call_with_args_parentheses.rb | lib/rubocop/cop/style/method_call_with_args_parentheses.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the presence (default) or absence of parentheses in
# method calls containing arguments.
#
# In the default style (require_parentheses), macro methods are allowed.
# Additional methods can be added to the `AllowedMethods` or
# `AllowedPatterns` list. These options are valid only in the default
# style. Macros can be included by either setting `IgnoreMacros` to false,
# adding specific macros to the `IncludedMacros` list, or using
# `IncludedMacroPatterns` for pattern-based matching.
#
# Precedence of options is as follows:
#
# 1. `AllowedMethods`
# 2. `AllowedPatterns`
# 3. `IncludedMacros`
# 4. `IncludedMacroPatterns`
#
# If a method is listed in both `IncludedMacros`/`IncludedMacroPatterns`
# and `AllowedMethods`, then the latter takes precedence (that is, the
# method is allowed).
#
# In the alternative style (omit_parentheses), there are three additional
# options.
#
# 1. `AllowParenthesesInChaining` is `false` by default. Setting it to
# `true` allows the presence of parentheses in the last call during
# method chaining.
#
# 2. `AllowParenthesesInMultilineCall` is `false` by default. Setting it
# to `true` allows the presence of parentheses in multi-line method
# calls.
#
# 3. `AllowParenthesesInCamelCaseMethod` is `false` by default. This
# allows the presence of parentheses when calling a method whose name
# begins with a capital letter and which has no arguments. Setting it
# to `true` allows the presence of parentheses in such a method call
# even with arguments.
#
# NOTE: The style of `omit_parentheses` allows parentheses in cases where
# omitting them results in ambiguous or syntactically incorrect code.
#
# Non-exhaustive list of examples:
#
# - Parentheses are required allowed in method calls with arguments inside
# literals, logical operators, setting default values in position and
# keyword arguments, chaining and more.
# - Parentheses are allowed in method calls with arguments inside
# operators to avoid ambiguity.
# triple-dot syntax introduced in Ruby 2.7 as omitting them starts an
# endless range.
# - Parentheses are allowed when forwarding arguments with the
# triple-dot syntax introduced in Ruby 2.7 as omitting them starts an
# endless range.
# - Parentheses are required in calls with arguments when inside an
# endless method definition introduced in Ruby 3.0.
# - Ruby 3.1's hash omission syntax allows parentheses if the method call
# is in conditionals and requires parentheses if the call
# is not the value-returning expression. See
# https://bugs.ruby-lang.org/issues/18396.
# - Parentheses are required in anonymous arguments, keyword arguments
# and block passing in Ruby 3.2.
# - Parentheses are required when the first argument is a beginless range or
# the last argument is an endless range.
#
# @example EnforcedStyle: require_parentheses (default)
#
# # bad
# array.delete e
#
# # good
# array.delete(e)
#
# # good
# # Operators don't need parens
# foo == bar
#
# # good
# # Setter methods don't need parens
# foo.bar = baz
#
# # okay with `puts` listed in `AllowedMethods`
# puts 'test'
#
# # okay with `^assert` listed in `AllowedPatterns`
# assert_equal 'test', x
#
# @example EnforcedStyle: omit_parentheses
#
# # bad
# array.delete(e)
#
# # good
# array.delete e
#
# # bad
# action.enforce(strict: true)
#
# # good
# action.enforce strict: true
#
# # good
# # Parentheses are allowed for code that can be ambiguous without
# # them.
# action.enforce(condition) || other_condition
#
# # good
# # Parentheses are allowed for calls that won't produce valid Ruby
# # without them.
# yield path, File.basename(path)
#
# # good
# # Omitting the parentheses in Ruby 3.1 hash omission syntax can lead
# # to ambiguous code. We allow them in conditionals and non-last
# # expressions. See https://bugs.ruby-lang.org/issues/18396
# if meets(criteria:, action:)
# safe_action(action) || dangerous_action(action)
# end
#
# @example IgnoreMacros: true (default)
#
# # good
# class Foo
# bar :baz
# end
#
# @example IgnoreMacros: false
#
# # bad
# class Foo
# bar :baz
# end
#
# @example AllowedMethods: ["puts", "print"]
#
# # good
# puts "Hello world"
# print "Hello world"
# # still enforces parentheses on other methods
# array.delete(e)
#
# @example AllowedPatterns: ["^assert"]
#
# # good
# assert_equal 'test', x
# assert_match(/foo/, bar)
# # still enforces parentheses on other methods
# array.delete(e)
#
# @example IncludedMacroPatterns: ["^assert", "^refute"]
#
# # bad
# assert_equal 'test', x
# refute_nil value
#
# # good
# assert_equal('test', x)
# refute_nil(value)
#
# @example AllowParenthesesInMultilineCall: false (default)
#
# # bad
# foo.enforce(
# strict: true
# )
#
# # good
# foo.enforce \
# strict: true
#
# @example AllowParenthesesInMultilineCall: true
#
# # good
# foo.enforce(
# strict: true
# )
#
# # good
# foo.enforce \
# strict: true
#
# @example AllowParenthesesInChaining: false (default)
#
# # bad
# foo().bar(1)
#
# # good
# foo().bar 1
#
# @example AllowParenthesesInChaining: true
#
# # good
# foo().bar(1)
#
# # good
# foo().bar 1
#
# @example AllowParenthesesInCamelCaseMethod: false (default)
#
# # bad
# Array(1)
#
# # good
# Array 1
#
# @example AllowParenthesesInCamelCaseMethod: true
#
# # good
# Array(1)
#
# # good
# Array 1
#
# @example AllowParenthesesInStringInterpolation: false (default)
#
# # bad
# "#{t('this.is.bad')}"
#
# # good
# "#{t 'this.is.better'}"
#
# @example AllowParenthesesInStringInterpolation: true
#
# # good
# "#{t('this.is.good')}"
#
# # good
# "#{t 'this.is.also.good'}"
class MethodCallWithArgsParentheses < Base
require_relative 'method_call_with_args_parentheses/omit_parentheses'
require_relative 'method_call_with_args_parentheses/require_parentheses'
include ConfigurableEnforcedStyle
include AllowedMethods
include AllowedPattern
include RequireParentheses
include OmitParentheses
extend AutoCorrector
def self.autocorrect_incompatible_with
[Style::NestedParenthesizedCalls, Style::RescueModifier]
end
def on_send(node)
send(style, node) # call require_parentheses or omit_parentheses
end
alias on_csend on_send
alias on_yield on_send
private
def args_begin(node)
loc = node.loc
selector = node.yield_type? ? loc.keyword : loc.selector
resize_by = args_parenthesized?(node) ? 2 : 1
selector.end.resize(resize_by)
end
def args_end(node)
node.source_range.end
end
def args_parenthesized?(node)
return false unless node.arguments.one?
first_node = node.first_argument
first_node.begin_type? && first_node.parenthesized_call?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/bare_percent_literals.rb | lib/rubocop/cop/style/bare_percent_literals.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks if usage of %() or %Q() matches configuration.
#
# @example EnforcedStyle: bare_percent (default)
# # bad
# %Q(He said: "#{greeting}")
# %q{She said: 'Hi'}
#
# # good
# %(He said: "#{greeting}")
# %{She said: 'Hi'}
#
# @example EnforcedStyle: percent_q
# # bad
# %|He said: "#{greeting}"|
# %/She said: 'Hi'/
#
# # good
# %Q|He said: "#{greeting}"|
# %q/She said: 'Hi'/
#
class BarePercentLiterals < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Use `%%%<good>s` instead of `%%%<bad>s`.'
def on_dstr(node)
check(node)
end
def on_str(node)
check(node)
end
private
def check(node)
return if node.heredoc?
return unless node.loc?(:begin)
source = node.loc.begin.source
if requires_percent_q?(source)
add_offense_for_wrong_style(node, 'Q', '')
elsif requires_bare_percent?(source)
add_offense_for_wrong_style(node, '', 'Q')
end
end
def requires_percent_q?(source)
style == :percent_q && /^%[^\w]/.match?(source)
end
def requires_bare_percent?(source)
style == :bare_percent && source.start_with?('%Q')
end
def add_offense_for_wrong_style(node, good, bad)
location = node.loc.begin
add_offense(location, message: format(MSG, good: good, bad: bad)) do |corrector|
source = location.source
replacement = source.start_with?('%Q') ? '%' : '%Q'
corrector.replace(location, source.sub(/%Q?/, replacement))
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/fetch_env_var.rb | lib/rubocop/cop/style/fetch_env_var.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Suggests `ENV.fetch` for the replacement of `ENV[]`.
# `ENV[]` silently fails and returns `nil` when the environment variable is unset,
# which may cause unexpected behaviors when the developer forgets to set it.
# On the other hand, `ENV.fetch` raises `KeyError` or returns the explicitly
# specified default value.
#
# @example DefaultToNil: true (default)
# # bad
# ENV['X']
# x = ENV['X']
#
# # good
# ENV.fetch('X', nil)
# x = ENV.fetch('X', nil)
#
# # also good
# !ENV['X']
# ENV['X'].some_method # (e.g. `.nil?`)
#
# @example DefaultToNil: false
# # bad
# ENV['X']
# x = ENV['X']
#
# # good
# ENV.fetch('X')
# x = ENV.fetch('X')
#
# # also good
# !ENV['X']
# ENV['X'].some_method # (e.g. `.nil?`)
#
class FetchEnvVar < Base
extend AutoCorrector
MSG_WITH_NIL = 'Use `ENV.fetch(%<key>s, nil)` instead of `ENV[%<key>s]`.'
MSG_WITHOUT_NIL = 'Use `ENV.fetch(%<key>s)` instead of `ENV[%<key>s]`.'
RESTRICT_ON_SEND = [:[]].freeze
# @!method env_with_bracket?(node)
def_node_matcher :env_with_bracket?, <<~PATTERN
(send (const nil? :ENV) :[] $_)
PATTERN
def on_send(node)
env_with_bracket?(node) do |name_node|
break unless offensive?(node)
message = format(offense_message, key: name_node.source)
add_offense(node, message: message) do |corrector|
corrector.replace(node, new_code(name_node))
end
end
end
private
def default_to_nil?
cop_config.fetch('DefaultToNil', true)
end
def offense_message
default_to_nil? ? MSG_WITH_NIL : MSG_WITHOUT_NIL
end
def allowed_var?(node)
env_key_node = node.children.last
env_key_node.str_type? && cop_config['AllowedVars'].include?(env_key_node.value)
end
def used_as_flag?(node)
return false if node.root?
return true if used_if_condition_in_body?(node)
node.parent.send_type? && (node.parent.prefix_bang? || node.parent.comparison_method?)
end
def used_if_condition_in_body?(node)
if_node = node.ancestors.find(&:if_type?)
return false unless (condition = if_node&.condition)
return true if condition.send_type? && (condition.child_nodes == node.child_nodes)
used_in_condition?(node, condition)
end
def used_in_condition?(node, condition)
if condition.send_type?
return true if condition.assignment_method? && partial_matched?(node, condition)
return false if !condition.comparison_method? && !condition.predicate_method?
end
condition.child_nodes.any?(node)
end
# Avoid offending in the following cases:
# `ENV['key'] if ENV['key'] = x`
def partial_matched?(node, condition)
node.child_nodes == node.child_nodes & condition.child_nodes
end
def offensive?(node)
!(allowed_var?(node) || allowable_use?(node))
end
# Check if the node is a receiver and receives a message with dot syntax.
def message_chained_with_dot?(node)
return false if node.root?
parent = node.parent
return false if !parent.call_type? || parent.children.first != node
parent.dot? || parent.safe_navigation?
end
# The following are allowed cases:
#
# - Used as a flag (e.g., `if ENV['X']` or `!ENV['X']`) because
# it simply checks whether the variable is set.
# - Receiving a message with dot syntax, e.g. `ENV['X'].nil?`.
# - `ENV['key']` assigned by logical AND/OR assignment.
# - `ENV['key']` is the LHS of a `||`.
def allowable_use?(node)
used_as_flag?(node) || message_chained_with_dot?(node) || assigned?(node) || or_lhs?(node)
end
# The following are allowed cases:
#
# - `ENV['key']` is a receiver of `||=`, e.g. `ENV['X'] ||= y`.
# - `ENV['key']` is a receiver of `&&=`, e.g. `ENV['X'] &&= y`.
def assigned?(node)
return false unless (parent = node.parent)&.assignment?
lhs, _method, _rhs = *parent
node == lhs
end
def or_lhs?(node)
return false unless (parent = node.parent)&.or_type?
parent.lhs == node || parent.parent&.or_type?
end
def new_code(name_node)
if default_to_nil?
"ENV.fetch(#{name_node.source}, nil)"
else
"ENV.fetch(#{name_node.source})"
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/frozen_string_literal_comment.rb | lib/rubocop/cop/style/frozen_string_literal_comment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Helps you transition from mutable string literals
# to frozen string literals.
# It will add the `# frozen_string_literal: true` magic comment to the top
# of files to enable frozen string literals. Frozen string literals may be
# default in future Ruby. The comment will be added below a shebang and
# encoding comment. The frozen string literal comment is only valid in Ruby 2.3+.
#
# Note that the cop will accept files where the comment exists but is set
# to `false` instead of `true`.
#
# To require a blank line after this comment, please see
# `Layout/EmptyLineAfterMagicComment` cop.
#
# @safety
# This cop's autocorrection is unsafe since any strings mutations will
# change from being accepted to raising `FrozenError`, as all strings
# will become frozen by default, and will need to be manually refactored.
#
# @example EnforcedStyle: always (default)
# # The `always` style will always add the frozen string literal comment
# # to a file, regardless of the Ruby version or if `freeze` or `<<` are
# # called on a string literal.
# # bad
# module Bar
# # ...
# end
#
# # good
# # frozen_string_literal: true
#
# module Bar
# # ...
# end
#
# # good
# # frozen_string_literal: false
#
# module Bar
# # ...
# end
#
# @example EnforcedStyle: never
# # The `never` will enforce that the frozen string literal comment does
# # not exist in a file.
# # bad
# # frozen_string_literal: true
#
# module Baz
# # ...
# end
#
# # good
# module Baz
# # ...
# end
#
# @example EnforcedStyle: always_true
# # The `always_true` style enforces that the frozen string literal
# # comment is set to `true`. This is a stricter option than `always`
# # and forces projects to use frozen string literals.
# # bad
# # frozen_string_literal: false
#
# module Baz
# # ...
# end
#
# # bad
# module Baz
# # ...
# end
#
# # good
# # frozen_string_literal: true
#
# module Bar
# # ...
# end
class FrozenStringLiteralComment < Base
include ConfigurableEnforcedStyle
include FrozenStringLiteral
include RangeHelp
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.3
MSG_MISSING_TRUE = 'Missing magic comment `# frozen_string_literal: true`.'
MSG_MISSING = 'Missing frozen string literal comment.'
MSG_UNNECESSARY = 'Unnecessary frozen string literal comment.'
MSG_DISABLED = 'Frozen string literal comment must be set to `true`.'
SHEBANG = '#!'
def on_new_investigation
return if processed_source.tokens.empty?
case style
when :never
ensure_no_comment(processed_source)
when :always_true
ensure_enabled_comment(processed_source)
else
ensure_comment(processed_source)
end
end
private
def ensure_no_comment(processed_source)
return unless frozen_string_literal_comment_exists?
unnecessary_comment_offense(processed_source)
end
def ensure_comment(processed_source)
return if frozen_string_literal_comment_exists?
missing_offense(processed_source)
end
def ensure_enabled_comment(processed_source)
if frozen_string_literal_specified?
return if frozen_string_literals_enabled?
# The comment exists, but is not enabled.
disabled_offense(processed_source)
else # The comment doesn't exist at all.
missing_true_offense(processed_source)
end
end
def last_special_comment(processed_source)
token_number = 0
if processed_source.tokens[token_number].text.start_with?(SHEBANG)
token = processed_source.tokens[token_number]
token_number += 1
end
next_token = processed_source.tokens[token_number]
if next_token&.text&.valid_encoding? && Encoding::ENCODING_PATTERN.match?(next_token.text)
token = next_token
end
token
end
def frozen_string_literal_comment(processed_source)
processed_source.tokens.find do |token|
MagicComment.parse(token.text).frozen_string_literal_specified?
end
end
def missing_offense(processed_source)
range = source_range(processed_source.buffer, 0, 0)
add_offense(range, message: MSG_MISSING) { |corrector| insert_comment(corrector) }
end
def missing_true_offense(processed_source)
range = source_range(processed_source.buffer, 0, 0)
add_offense(range, message: MSG_MISSING_TRUE) { |corrector| insert_comment(corrector) }
end
def unnecessary_comment_offense(processed_source)
frozen_string_literal_comment = frozen_string_literal_comment(processed_source)
add_offense(frozen_string_literal_comment.pos, message: MSG_UNNECESSARY) do |corrector|
remove_comment(corrector, frozen_string_literal_comment)
end
end
def disabled_offense(processed_source)
frozen_string_literal_comment = frozen_string_literal_comment(processed_source)
add_offense(frozen_string_literal_comment.pos, message: MSG_DISABLED) do |corrector|
enable_comment(corrector)
end
end
def remove_comment(corrector, node)
corrector.remove(range_with_surrounding_space(node.pos, side: :right))
end
def enable_comment(corrector)
comment = frozen_string_literal_comment(processed_source)
replacement = MagicComment.parse(comment.text).new_frozen_string_literal(true)
corrector.replace(line_range(comment.line), replacement)
end
def insert_comment(corrector)
comment = last_special_comment(processed_source)
if comment
corrector.insert_after(line_range(comment.line), following_comment)
else
corrector.insert_before(processed_source.buffer.source_range, preceding_comment)
end
end
def line_range(line)
processed_source.buffer.line_range(line)
end
def preceding_comment
"#{FROZEN_STRING_LITERAL_ENABLED}\n"
end
def following_comment
"\n#{FROZEN_STRING_LITERAL_ENABLED}"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/nested_modifier.rb | lib/rubocop/cop/style/nested_modifier.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for nested use of if, unless, while and until in their
# modifier form.
#
# @example
#
# # bad
# something if a if b
#
# # good
# something if b && a
class NestedModifier < Base
include RangeHelp
extend AutoCorrector
MSG = 'Avoid using nested modifiers.'
def on_while(node)
check(node)
end
alias on_until on_while
alias on_if on_while
private
def check(node)
return if part_of_ignored_node?(node)
return unless modifier?(node) && modifier?(node.parent)
add_offense(node.loc.keyword) { |corrector| autocorrect(corrector, node) }
ignore_node(node)
end
def modifier?(node)
node&.basic_conditional? && node.modifier_form?
end
def autocorrect(corrector, node)
return unless node.if_type? && node.parent.if_type?
range = range_between(node.loc.keyword.begin_pos,
node.parent.condition.source_range.end_pos)
corrector.replace(range, new_expression(node))
end
def new_expression(inner_node)
outer_node = inner_node.parent
operator = replacement_operator(outer_node.keyword)
lh_operand = left_hand_operand(outer_node, operator)
rh_operand = right_hand_operand(inner_node, outer_node.keyword)
"#{outer_node.keyword} #{lh_operand} #{operator} #{rh_operand}"
end
def replacement_operator(keyword)
keyword == 'if' ? '&&' : '||'
end
def left_hand_operand(node, operator)
expr = node.condition.source
expr = "(#{expr})" if node.condition.or_type? && operator == '&&'
expr
end
def right_hand_operand(node, left_hand_keyword)
condition = node.condition
expr = if condition.send_type? && !condition.arguments.empty? &&
!condition.operator_method?
add_parentheses_to_method_arguments(condition)
else
condition.source
end
expr = "(#{expr})" if requires_parens?(condition)
expr = "!#{expr}" unless left_hand_keyword == node.keyword
expr
end
def add_parentheses_to_method_arguments(send_node)
expr = +''
expr << "#{send_node.receiver.source}." if send_node.receiver
expr << send_node.method_name.to_s
expr << "(#{send_node.arguments.map(&:source).join(', ')})"
expr
end
def requires_parens?(node)
node.or_type? || !(RuboCop::AST::Node::COMPARISON_OPERATORS & node.children).empty?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/collection_compact.rb | lib/rubocop/cop/style/collection_compact.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where custom logic on rejection nils from arrays
# and hashes can be replaced with `{Array,Hash}#{compact,compact!}`.
#
# @safety
# It is unsafe by default because false positives may occur in the
# `nil` check of block arguments to the receiver object. Additionally,
# we can't know the type of the receiver object for sure, which may
# result in false positives as well.
#
# For example, `[[1, 2], [3, nil]].reject { |first, second| second.nil? }`
# and `[[1, 2], [3, nil]].compact` are not compatible. This will work fine
# when the receiver is a hash object.
#
# @example
# # bad
# array.reject(&:nil?)
# array.reject { |e| e.nil? }
# array.select { |e| !e.nil? }
# array.filter { |e| !e.nil? }
# array.grep_v(nil)
# array.grep_v(NilClass)
#
# # good
# array.compact
#
# # bad
# hash.reject!(&:nil?)
# hash.reject! { |k, v| v.nil? }
# hash.select! { |k, v| !v.nil? }
# hash.filter! { |k, v| !v.nil? }
#
# # good
# hash.compact!
#
# @example AllowedReceivers: ['params']
# # good
# params.reject(&:nil?)
#
class CollectionCompact < Base
include AllowedReceivers
include RangeHelp
extend AutoCorrector
extend TargetRubyVersion
MSG = 'Use `%<good>s` instead of `%<bad>s`.'
RESTRICT_ON_SEND = %i[reject reject! select select! filter filter! grep_v].freeze
TO_ENUM_METHODS = %i[to_enum lazy].freeze
FILTER_METHODS = %i[filter filter!].freeze
minimum_target_ruby_version 2.4
# @!method reject_method_with_block_pass?(node)
def_node_matcher :reject_method_with_block_pass?, <<~PATTERN
(call !nil? {:reject :reject!}
(block_pass
(sym :nil?)))
PATTERN
# @!method reject_method?(node)
def_node_matcher :reject_method?, <<~PATTERN
(block
(call
!nil? {:reject :reject!})
$(args ...)
(call
$(lvar _) :nil?))
PATTERN
# @!method select_method?(node)
def_node_matcher :select_method?, <<~PATTERN
(block
(call
!nil? {:select :select! :filter :filter!})
$(args ...)
(call
(call
$(lvar _) :nil?) :!))
PATTERN
# @!method grep_v_with_nil?(node)
def_node_matcher :grep_v_with_nil?, <<~PATTERN
(send _ :grep_v {(nil) (const {nil? cbase} :NilClass)})
PATTERN
def on_send(node)
return if target_ruby_version < 2.6 && FILTER_METHODS.include?(node.method_name)
return unless (range = offense_range(node))
return if allowed_receiver?(node.receiver)
return if target_ruby_version <= 3.0 && to_enum_method?(node)
good = good_method_name(node)
message = format(MSG, good: good, bad: range.source)
add_offense(range, message: message) { |corrector| corrector.replace(range, good) }
end
alias on_csend on_send
private
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def offense_range(node)
if reject_method_with_block_pass?(node) || grep_v_with_nil?(node)
range(node, node)
else
block_node = node.parent
return unless block_node&.block_type?
unless (args, receiver = reject_method?(block_node) || select_method?(block_node))
return
end
return unless args.last.source == receiver.source
range(node, block_node)
end
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def to_enum_method?(node)
return false unless node.receiver.send_type?
TO_ENUM_METHODS.include?(node.receiver.method_name)
end
def good_method_name(node)
if node.bang_method?
'compact!'
else
'compact'
end
end
def range(begin_pos_node, end_pos_node)
range_between(begin_pos_node.loc.selector.begin_pos, end_pos_node.source_range.end_pos)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/if_unless_modifier_of_if_unless.rb | lib/rubocop/cop/style/if_unless_modifier_of_if_unless.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for if and unless statements used as modifiers of other if or
# unless statements.
#
# @example
#
# # bad
# tired? ? 'stop' : 'go faster' if running?
#
# # bad
# if tired?
# "please stop"
# else
# "keep going"
# end if running?
#
# # good
# if running?
# tired? ? 'stop' : 'go faster'
# end
class IfUnlessModifierOfIfUnless < Base
include StatementModifier
extend AutoCorrector
MSG = 'Avoid modifier `%<keyword>s` after another conditional.'
# rubocop:disable Metrics/AbcSize
def on_if(node)
return unless node.modifier_form? && node.body.if_type?
add_offense(node.loc.keyword, message: format(MSG, keyword: node.keyword)) do |corrector|
corrector.wrap(node.if_branch, "#{node.keyword} #{node.condition.source}\n", "\nend")
corrector.remove(node.if_branch.source_range.end.join(node.condition.source_range.end))
end
end
# rubocop:enable Metrics/AbcSize
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/combinable_defined.rb | lib/rubocop/cop/style/combinable_defined.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for multiple `defined?` calls joined by `&&` that can be combined
# into a single `defined?`.
#
# When checking that a nested constant or chained method is defined, it is
# not necessary to check each ancestor or component of the chain.
#
# @example
# # bad
# defined?(Foo) && defined?(Foo::Bar) && defined?(Foo::Bar::Baz)
#
# # good
# defined?(Foo::Bar::Baz)
#
# # bad
# defined?(foo) && defined?(foo.bar) && defined?(foo.bar.baz)
#
# # good
# defined?(foo.bar.baz)
class CombinableDefined < Base
extend AutoCorrector
include RangeHelp
MSG = 'Combine nested `defined?` calls.'
OPERATORS = %w[&& and].freeze
def on_and(node)
# Only register an offense if all `&&` terms are `defined?` calls
return unless (terms = terms(node)).all?(&:defined_type?)
calls = defined_calls(terms)
namespaces = namespaces(calls)
calls.each do |call|
next unless namespaces.any?(call)
add_offense(node) do |corrector|
remove_term(corrector, call)
end
end
end
private
def terms(node)
node.each_descendant.select do |descendant|
descendant.parent.and_type? && !descendant.and_type?
end
end
def defined_calls(nodes)
nodes.filter_map do |defined_node|
subject = defined_node.first_argument
subject if subject.type?(:const, :call)
end
end
def namespaces(nodes)
nodes.filter_map do |node|
if node.respond_to?(:namespace)
node.namespace
elsif node.respond_to?(:receiver)
node.receiver
end
end
end
def remove_term(corrector, term)
term = term.parent until term.parent.and_type?
range = if term == term.parent.children.last
rhs_range_to_remove(term)
else
lhs_range_to_remove(term)
end
corrector.remove(range)
end
# If the redundant `defined?` node is the LHS of an `and` node,
# the term as well as the subsequent `&&`/`and` operator will be removed.
def lhs_range_to_remove(term)
source = @processed_source.buffer.source
pos = term.source_range.end_pos
pos += 1 until source[..pos].end_with?(*OPERATORS)
range_with_surrounding_space(
range: term.source_range.with(end_pos: pos + 1),
side: :right,
newlines: false
)
end
# If the redundant `defined?` node is the RHS of an `and` node,
# the term as well as the preceding `&&`/`and` operator will be removed.
def rhs_range_to_remove(term)
source = @processed_source.buffer.source
pos = term.source_range.begin_pos
pos -= 1 until source[pos, 3].start_with?(*OPERATORS)
range_with_surrounding_space(
range: term.source_range.with(begin_pos: pos - 1),
side: :right,
newlines: false
)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/percent_literal_delimiters.rb | lib/rubocop/cop/style/percent_literal_delimiters.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the consistent usage of `%`-literal delimiters.
#
# Specify the 'default' key to set all preferred delimiters at once. You
# can continue to specify individual preferred delimiters to override the
# default.
#
# @example
# # Style/PercentLiteralDelimiters:
# # PreferredDelimiters:
# # default: '[]'
# # '%i': '()'
#
# # good
# %w[alpha beta] + %i(gamma delta)
#
# # bad
# %W(alpha #{beta})
#
# # bad
# %I(alpha beta)
class PercentLiteralDelimiters < Base
include PercentLiteral
extend AutoCorrector
def on_array(node)
process(node, '%w', '%W', '%i', '%I')
end
def on_regexp(node)
process(node, '%r')
end
def on_str(node)
process(node, '%', '%Q', '%q')
end
alias on_dstr on_str
def on_sym(node)
process(node, '%s')
end
def on_xstr(node)
process(node, '%x')
end
private
def on_percent_literal(node)
type = type(node)
return if uses_preferred_delimiter?(node, type) ||
contains_preferred_delimiter?(node, type) ||
include_same_character_as_used_for_delimiter?(node, type)
add_offense(node, message: message(type)) do |corrector|
opening_delimiter, closing_delimiter = preferred_delimiters_for(type)
corrector.replace(node.loc.begin, "#{type}#{opening_delimiter}")
corrector.replace(node.loc.end, closing_delimiter)
end
end
def message(type)
delimiters = preferred_delimiters_for(type)
"`#{type}`-literals should be delimited by " \
"`#{delimiters[0]}` and `#{delimiters[1]}`."
end
def preferred_delimiters_for(type)
PreferredDelimiters.new(type, @config, nil).delimiters
end
def uses_preferred_delimiter?(node, type)
preferred_delimiters_for(type)[0] == begin_source(node)[-1]
end
def contains_preferred_delimiter?(node, type)
contains_delimiter?(node, preferred_delimiters_for(type))
end
def include_same_character_as_used_for_delimiter?(node, type)
return false unless %w[%w %i].include?(type)
used_delimiters = matchpairs(begin_source(node)[-1])
contains_delimiter?(node, used_delimiters)
end
def contains_delimiter?(node, delimiters)
delimiters_regexp = Regexp.union(delimiters)
node.children.filter_map { |n| string_source(n) }.any?(delimiters_regexp)
end
def string_source(node)
if node.is_a?(String)
node.scrub
elsif node.respond_to?(:type) && node.type?(:str, :sym)
node.source
end
end
def matchpairs(begin_delimiter)
{
'(' => %w[( )],
'[' => %w[[ ]],
'{' => %w[{ }],
'<' => %w[< >]
}.fetch(begin_delimiter, [begin_delimiter])
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_regexp_argument.rb | lib/rubocop/cop/style/redundant_regexp_argument.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Identifies places where argument can be replaced from
# a deterministic regexp to a string.
#
# @example
# # bad
# 'foo'.byteindex(/f/)
# 'foo'.byterindex(/f/)
# 'foo'.gsub(/f/, 'x')
# 'foo'.gsub!(/f/, 'x')
# 'foo'.partition(/f/)
# 'foo'.rpartition(/f/)
# 'foo'.scan(/f/)
# 'foo'.split(/f/)
# 'foo'.start_with?(/f/)
# 'foo'.sub(/f/, 'x')
# 'foo'.sub!(/f/, 'x')
#
# # good
# 'foo'.byteindex('f')
# 'foo'.byterindex('f')
# 'foo'.gsub('f', 'x')
# 'foo'.gsub!('f', 'x')
# 'foo'.partition('f')
# 'foo'.rpartition('f')
# 'foo'.scan('f')
# 'foo'.split('f')
# 'foo'.start_with?('f')
# 'foo'.sub('f', 'x')
# 'foo'.sub!('f', 'x')
class RedundantRegexpArgument < Base
include StringLiteralsHelp
extend AutoCorrector
MSG = 'Use string `%<prefer>s` as argument instead of regexp `%<current>s`.'
RESTRICT_ON_SEND = %i[
byteindex byterindex gsub gsub! partition rpartition scan split start_with? sub sub!
].freeze
DETERMINISTIC_REGEX = /\A(?:#{LITERAL_REGEX})+\Z/.freeze
STR_SPECIAL_CHARS = %w[
\a \c \C \e \f \M \n \" \' \\\\ \t \b \f \r \u \v \x \0 \1 \2 \3 \4 \5 \6 \7
].freeze
def on_send(node)
return unless (regexp_node = node.first_argument)
return unless regexp_node.regexp_type?
return if !regexp_node.regopt.children.empty? || regexp_node.content == ' '
return unless determinist_regexp?(regexp_node)
prefer = preferred_argument(regexp_node)
message = format(MSG, prefer: prefer, current: regexp_node.source)
add_offense(regexp_node, message: message) do |corrector|
corrector.replace(regexp_node, prefer)
end
end
alias on_csend on_send
private
def determinist_regexp?(regexp_node)
DETERMINISTIC_REGEX.match?(regexp_node.source)
end
# rubocop:disable Metrics/MethodLength
def preferred_argument(regexp_node)
new_argument = replacement(regexp_node)
if new_argument.include?('"')
new_argument.gsub!("'", "\\\\'")
new_argument.gsub!('\"', '"')
quote = "'"
elsif new_argument.include?("\\'")
# Add a backslash before single quotes preceded by an even number of backslashes.
# An even number (including zero) of backslashes before a quote means the quote itself
# is not escaped.
# Otherwise an odd number means the quote is already escaped so this doesn't touch it.
new_argument.gsub!(/(?<!\\)((?:\\\\)*)'/) { "#{::Regexp.last_match(1)}\\'" }
quote = "'"
elsif new_argument.include?('\'')
new_argument.gsub!("'", "\\\\'")
quote = "'"
elsif new_argument.include?('\\')
quote = '"'
else
quote = enforce_double_quotes? ? '"' : "'"
end
"#{quote}#{new_argument}#{quote}"
end
# rubocop:enable Metrics/MethodLength
def replacement(regexp_node)
regexp_content = regexp_node.content
stack = []
chars = regexp_content.chars.each_with_object([]) do |char, strings|
if stack.empty? && char == '\\'
stack.push(char)
else
strings << "#{stack.pop}#{char}"
end
end
chars.map do |char|
char = char.dup
char.delete!('\\') unless STR_SPECIAL_CHARS.include?(char)
char
end.join
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/perl_backrefs.rb | lib/rubocop/cop/style/perl_backrefs.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for uses of Perl-style regexp match
# backreferences and their English versions like
# $1, $2, $&, &+, $MATCH, $PREMATCH, etc.
#
# @example
# # bad
# puts $1
#
# # good
# puts Regexp.last_match(1)
class PerlBackrefs < Base
extend AutoCorrector
MESSAGE_FORMAT = 'Prefer `%<preferred_expression>s` over `%<original_expression>s`.'
def on_back_ref(node)
on_back_ref_or_gvar_or_nth_ref(node)
end
def on_gvar(node)
on_back_ref_or_gvar_or_nth_ref(node)
end
def on_nth_ref(node)
on_back_ref_or_gvar_or_nth_ref(node)
end
private
# @private
# @param [RuboCop::AST::Node] node
# @return [Boolean]
def derived_from_braceless_interpolation?(node)
%i[dstr regexp xstr].include?(node.parent&.type)
end
# @private
# @param [RuboCop::AST::Node] node
# @param [String] preferred_expression
# @return [String]
def format_message(node:, preferred_expression:)
original_expression = original_expression_of(node)
format(
MESSAGE_FORMAT,
original_expression: original_expression,
preferred_expression: preferred_expression
)
end
# @private
# @param [RuboCop::AST::Node] node
# @return [String]
def original_expression_of(node)
first = node.to_a.first
if first.is_a?(::Integer)
"$#{first}"
else
first.to_s
end
end
# @private
# @param [RuboCop::AST::Node] node
# @return [String, nil]
def preferred_expression_to(node)
first = node.to_a.first
case first
when ::Integer
"Regexp.last_match(#{first})"
when :$&, :$MATCH
'Regexp.last_match(0)'
when :$`, :$PREMATCH
'Regexp.last_match.pre_match'
when :$', :$POSTMATCH
'Regexp.last_match.post_match'
when :$+, :$LAST_PAREN_MATCH
'Regexp.last_match(-1)'
end
end
# @private
# @param [RuboCop::AST::Node] node
# @return [String, nil]
def preferred_expression_to_node_with_constant_prefix(node)
expression = preferred_expression_to(node)
return unless expression
"#{constant_prefix(node)}#{expression}"
end
# @private
# @param [RuboCop::AST::Node] node
# @return [String]
def constant_prefix(node)
if node.each_ancestor(:class, :module).any?
'::'
else
''
end
end
# @private
# @param [RuboCop::AST::Node] node
def on_back_ref_or_gvar_or_nth_ref(node)
preferred_expression = preferred_expression_to_node_with_constant_prefix(node)
return unless preferred_expression
add_offense(
node,
message: format_message(node: node, preferred_expression: preferred_expression)
) do |corrector|
if derived_from_braceless_interpolation?(node)
preferred_expression = "{#{preferred_expression}}"
end
corrector.replace(node, preferred_expression)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/trivial_accessors.rb | lib/rubocop/cop/style/trivial_accessors.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for trivial reader/writer methods, that could
# have been created with the attr_* family of functions automatically.
# `to_ary`, `to_a`, `to_c`, `to_enum`, `to_h`, `to_hash`, `to_i`, `to_int`, `to_io`,
# `to_open`, `to_path`, `to_proc`, `to_r`, `to_regexp`, `to_str`, `to_s`, and `to_sym` methods
# are allowed by default. These are customizable with `AllowedMethods` option.
#
# @example
# # bad
# def foo
# @foo
# end
#
# def bar=(val)
# @bar = val
# end
#
# def self.baz
# @baz
# end
#
# # good
# attr_reader :foo
# attr_writer :bar
#
# class << self
# attr_reader :baz
# end
#
# @example ExactNameMatch: true (default)
# # good
# def name
# @other_name
# end
#
# @example ExactNameMatch: false
# # bad
# def name
# @other_name
# end
#
# @example AllowPredicates: true (default)
# # good
# def foo?
# @foo
# end
#
# @example AllowPredicates: false
# # bad
# def foo?
# @foo
# end
#
# # good
# attr_reader :foo
#
# @example AllowDSLWriters: true (default)
# # good
# def on_exception(action)
# @on_exception=action
# end
#
# @example AllowDSLWriters: false
# # bad
# def on_exception(action)
# @on_exception=action
# end
#
# # good
# attr_writer :on_exception
#
# @example IgnoreClassMethods: false (default)
# # bad
# def self.foo
# @foo
# end
#
# # good
# class << self
# attr_reader :foo
# end
#
# @example IgnoreClassMethods: true
# # good
# def self.foo
# @foo
# end
#
# @example AllowedMethods: ['allowed_method']
# # good
# def allowed_method
# @foo
# end
class TrivialAccessors < Base
include AllowedMethods
extend AutoCorrector
MSG = 'Use `attr_%<kind>s` to define trivial %<kind>s methods.'
def on_def(node)
return if top_level_node?(node)
return if in_module_or_instance_eval?(node)
return if ignore_class_methods? && node.defs_type?
on_method_def(node)
end
alias on_defs on_def
private
def in_module_or_instance_eval?(node)
node.each_ancestor(:any_block, :class, :sclass, :module).each do |pnode|
case pnode.type
when :class, :sclass
return false
when :module
return true
else
return true if pnode.method?(:instance_eval)
end
end
false
end
def on_method_def(node)
kind = if trivial_reader?(node)
'reader'
elsif trivial_writer?(node)
'writer'
end
return unless kind
add_offense(node.loc.keyword, message: format(MSG, kind: kind)) do |corrector|
autocorrect(corrector, node)
end
end
def autocorrect(corrector, node)
parent = node.parent
return if parent&.send_type?
if node.def_type?
autocorrect_instance(corrector, node)
elsif node.defs_type? && node.children.first.self_type?
autocorrect_class(corrector, node)
end
end
def exact_name_match?
cop_config['ExactNameMatch']
end
def allow_predicates?
cop_config['AllowPredicates']
end
def allow_dsl_writers?
cop_config['AllowDSLWriters']
end
def ignore_class_methods?
cop_config['IgnoreClassMethods']
end
def allowed_method_names
allowed_methods.map(&:to_sym) + [:initialize]
end
def dsl_writer?(node)
!node.assignment_method?
end
def trivial_reader?(node)
looks_like_trivial_reader?(node) && !allowed_method_name?(node) && !allowed_reader?(node)
end
def looks_like_trivial_reader?(node)
!node.arguments? && node.body&.ivar_type?
end
def trivial_writer?(node)
looks_like_trivial_writer?(node) && !allowed_method_name?(node) && !allowed_writer?(node)
end
# @!method looks_like_trivial_writer?(node)
def_node_matcher :looks_like_trivial_writer?, <<~PATTERN
{(def _ (args (arg ...)) (ivasgn _ (lvar _)))
(defs _ _ (args (arg ...)) (ivasgn _ (lvar _)))}
PATTERN
def allowed_method_name?(node)
allowed_method_names.include?(node.method_name) ||
(exact_name_match? && !names_match?(node))
end
def allowed_writer?(node)
allow_dsl_writers? && dsl_writer?(node)
end
def allowed_reader?(node)
allow_predicates? && node.predicate_method?
end
def names_match?(node)
ivar_name, = *node.body
node.method_name.to_s.sub(/[=?]$/, '') == ivar_name[1..]
end
def trivial_accessor_kind(node)
if trivial_writer?(node) && !dsl_writer?(node)
'writer'
elsif trivial_reader?(node)
'reader'
end
end
def accessor(kind, method_name)
"attr_#{kind} :#{method_name.to_s.chomp('=')}"
end
def autocorrect_instance(corrector, node)
kind = trivial_accessor_kind(node)
return unless names_match?(node) && !node.predicate_method? && kind
corrector.replace(node, accessor(kind, node.method_name))
end
def autocorrect_class(corrector, node)
kind = trivial_accessor_kind(node)
return unless names_match?(node) && kind
indent = ' ' * node.loc.column
corrector.replace(
node,
['class << self',
"#{indent} #{accessor(kind, node.method_name)}",
"#{indent}end"].join("\n")
)
end
def top_level_node?(node)
node.parent.nil?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/arguments_forwarding.rb | lib/rubocop/cop/style/arguments_forwarding.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# In Ruby 2.7, arguments forwarding has been added.
#
# This cop identifies places where `do_something(*args, &block)`
# can be replaced by `do_something(...)`.
#
# In Ruby 3.1, anonymous block forwarding has been added.
#
# This cop identifies places where `do_something(&block)` can be replaced
# by `do_something(&)`; if desired, this functionality can be disabled
# by setting `UseAnonymousForwarding: false`.
#
# In Ruby 3.2, anonymous args/kwargs forwarding has been added.
#
# This cop also identifies places where `+use_args(*args)+`/`+use_kwargs(**kwargs)+` can be
# replaced by `+use_args(*)+`/`+use_kwargs(**)+`; if desired, this functionality can be
# disabled by setting `UseAnonymousForwarding: false`.
#
# And this cop has `RedundantRestArgumentNames`, `RedundantKeywordRestArgumentNames`,
# and `RedundantBlockArgumentNames` options. This configuration is a list of redundant names
# that are sufficient for anonymizing meaningless naming.
#
# Meaningless names that are commonly used can be anonymized by default:
# e.g., `+*args+`, `+**options+`, `&block`, and so on.
#
# Names not on this list are likely to be meaningful and are allowed by default.
#
# This cop handles not only method forwarding but also forwarding to `super`.
#
# [NOTE]
# ====
# Because of a bug in Ruby 3.3.0, when a block is referenced inside of another block,
# no offense will be registered until Ruby 3.4:
#
# [source,ruby]
# ----
# def foo(&block)
# # Using an anonymous block would be a syntax error on Ruby 3.3.0
# block_method { bar(&block) }
# end
# ----
# ====
#
# @example
# # bad
# def foo(*args, &block)
# bar(*args, &block)
# end
#
# # bad
# def foo(*args, **kwargs, &block)
# bar(*args, **kwargs, &block)
# end
#
# # good
# def foo(...)
# bar(...)
# end
#
# @example UseAnonymousForwarding: true (default, only relevant for Ruby >= 3.2)
# # bad
# def foo(*args, **kwargs, &block)
# args_only(*args)
# kwargs_only(**kwargs)
# block_only(&block)
# end
#
# # good
# def foo(*, **, &)
# args_only(*)
# kwargs_only(**)
# block_only(&)
# end
#
# @example UseAnonymousForwarding: false (only relevant for Ruby >= 3.2)
# # good
# def foo(*args, **kwargs, &block)
# args_only(*args)
# kwargs_only(**kwargs)
# block_only(&block)
# end
#
# @example AllowOnlyRestArgument: true (default, only relevant for Ruby < 3.2)
# # good
# def foo(*args)
# bar(*args)
# end
#
# def foo(**kwargs)
# bar(**kwargs)
# end
#
# @example AllowOnlyRestArgument: false (only relevant for Ruby < 3.2)
# # bad
# # The following code can replace the arguments with `...`,
# # but it will change the behavior. Because `...` forwards block also.
# def foo(*args)
# bar(*args)
# end
#
# def foo(**kwargs)
# bar(**kwargs)
# end
#
# @example RedundantRestArgumentNames: ['args', 'arguments'] (default)
# # bad
# def foo(*args)
# bar(*args)
# end
#
# # good
# def foo(*)
# bar(*)
# end
#
# @example RedundantKeywordRestArgumentNames: ['kwargs', 'options', 'opts'] (default)
# # bad
# def foo(**kwargs)
# bar(**kwargs)
# end
#
# # good
# def foo(**)
# bar(**)
# end
#
# @example RedundantBlockArgumentNames: ['blk', 'block', 'proc'] (default)
# # bad - But it is good with `EnforcedStyle: explicit` set for `Naming/BlockForwarding`.
# def foo(&block)
# bar(&block)
# end
#
# # good
# def foo(&)
# bar(&)
# end
class ArgumentsForwarding < Base
include RangeHelp
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.7
FORWARDING_LVAR_TYPES = %i[splat kwsplat block_pass].freeze
FORWARDING_MSG = 'Use shorthand syntax `...` for arguments forwarding.'
ARGS_MSG = 'Use anonymous positional arguments forwarding (`*`).'
KWARGS_MSG = 'Use anonymous keyword arguments forwarding (`**`).'
BLOCK_MSG = 'Use anonymous block arguments forwarding (`&`).'
def self.autocorrect_incompatible_with
[Naming::BlockForwarding]
end
def on_def(node)
return unless node.body
restarg, kwrestarg, blockarg = extract_forwardable_args(node.arguments)
forwardable_args = redundant_forwardable_named_args(restarg, kwrestarg, blockarg)
send_nodes = node.each_descendant(:call, :super, :yield).to_a
send_classifications = classify_send_nodes(
node, send_nodes, non_splat_or_block_pass_lvar_references(node.body), forwardable_args
)
return if send_classifications.empty?
if only_forwards_all?(send_classifications)
add_forward_all_offenses(node, send_classifications, forwardable_args)
elsif target_ruby_version >= 3.2
add_post_ruby_32_offenses(node, send_classifications, forwardable_args)
end
end
alias on_defs on_def
private
def extract_forwardable_args(args)
[args.find(&:restarg_type?), args.find(&:kwrestarg_type?), args.find(&:blockarg_type?)]
end
def redundant_forwardable_named_args(restarg, kwrestarg, blockarg)
restarg_node = redundant_named_arg(restarg, 'RedundantRestArgumentNames', '*')
kwrestarg_node = redundant_named_arg(kwrestarg, 'RedundantKeywordRestArgumentNames', '**')
blockarg_node = redundant_named_arg(blockarg, 'RedundantBlockArgumentNames', '&')
[restarg_node, kwrestarg_node, blockarg_node]
end
def only_forwards_all?(send_classifications)
all_classifications = %i[all all_anonymous].freeze
send_classifications.all? { |_, c, _, _| all_classifications.include?(c) }
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
def add_forward_all_offenses(node, send_classifications, forwardable_args)
rest_arg, kwrest_arg, block_arg = *forwardable_args
registered_block_arg_offense = false
send_classifications.each do |send_node, c, forward_rest, forward_kwrest, forward_block_arg| # rubocop:disable Layout/LineLength
if !forward_rest && !forward_kwrest && c != :all_anonymous
if allow_anonymous_forwarding_in_block?(forward_block_arg)
register_forward_block_arg_offense(!forward_rest, node.arguments, block_arg)
register_forward_block_arg_offense(!forward_rest, send_node, forward_block_arg)
end
registered_block_arg_offense = true
break
else
first_arg = forward_rest || forward_kwrest || forward_all_first_argument(send_node)
register_forward_all_offense(send_node, send_node, first_arg)
end
end
return if registered_block_arg_offense
register_forward_all_offense(node, node.arguments, rest_arg || kwrest_arg)
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
def forward_all_first_argument(node)
node.arguments.reverse_each.find(&:forwarded_restarg_type?)
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def add_post_ruby_32_offenses(def_node, send_classifications, forwardable_args)
return unless use_anonymous_forwarding?
return unless all_forwarding_offenses_correctable?(send_classifications)
rest_arg, kwrest_arg, block_arg = *forwardable_args
send_classifications.each do |send_node, _c, forward_rest, forward_kwrest, forward_block_arg| # rubocop:disable Layout/LineLength
if allow_anonymous_forwarding_in_block?(forward_rest)
register_forward_args_offense(def_node.arguments, rest_arg)
register_forward_args_offense(send_node, forward_rest)
end
if allow_anonymous_forwarding_in_block?(forward_kwrest)
register_forward_kwargs_offense(!forward_rest, def_node.arguments, kwrest_arg)
register_forward_kwargs_offense(!forward_rest, send_node, forward_kwrest)
end
if allow_anonymous_forwarding_in_block?(forward_block_arg)
register_forward_block_arg_offense(!forward_rest, def_node.arguments, block_arg)
register_forward_block_arg_offense(!forward_rest, send_node, forward_block_arg)
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
def non_splat_or_block_pass_lvar_references(body)
body.each_descendant(:lvar, :lvasgn).filter_map do |lvar|
parent = lvar.parent
next if lvar.lvar_type? && FORWARDING_LVAR_TYPES.include?(parent.type)
lvar.children.first
end.uniq
end
def classify_send_nodes(def_node, send_nodes, referenced_lvars, forwardable_args)
send_nodes.filter_map do |send_node|
classification_and_forwards = classification_and_forwards(
def_node,
send_node,
referenced_lvars,
forwardable_args
)
next unless classification_and_forwards
[send_node, *classification_and_forwards]
end
end
def classification_and_forwards(def_node, send_node, referenced_lvars, forwardable_args)
classifier = SendNodeClassifier.new(
def_node, send_node, referenced_lvars, forwardable_args,
target_ruby_version: target_ruby_version,
allow_only_rest_arguments: allow_only_rest_arguments?
)
classification = classifier.classification
return unless classification
[
classification,
classifier.forwarded_rest_arg,
classifier.forwarded_kwrest_arg,
classifier.forwarded_block_arg
]
end
def redundant_named_arg(arg, config_name, keyword)
return nil unless arg
redundant_arg_names = cop_config.fetch(config_name, []).map do |redundant_arg_name|
"#{keyword}#{redundant_arg_name}"
end << keyword
redundant_arg_names.include?(arg.source) ? arg : nil
end
# Checks if forwarding is uses both in blocks and outside of blocks.
# On Ruby 3.3.0, anonymous block forwarding in blocks can be is a syntax
# error, so we only want to register an offense if we can change all occurrences.
def all_forwarding_offenses_correctable?(send_classifications)
return true if target_ruby_version >= 3.4
send_classifications.none? do |send_node, *|
send_node.each_ancestor(:any_block).any?
end
end
# Ruby 3.3.0 had a bug where accessing an anonymous block argument inside of a block
# was a syntax error in unambiguous cases: https://bugs.ruby-lang.org/issues/20090
# We disallow this also for earlier Ruby versions so that code is forwards compatible.
def allow_anonymous_forwarding_in_block?(node)
return false unless node
return true if target_ruby_version >= 3.4
node.each_ancestor(:any_block).none?
end
def register_forward_args_offense(def_arguments_or_send, rest_arg_or_splat)
add_offense(rest_arg_or_splat, message: ARGS_MSG) do |corrector|
add_parens_if_missing(def_arguments_or_send, corrector)
corrector.replace(rest_arg_or_splat, '*')
end
end
def register_forward_kwargs_offense(add_parens, def_arguments_or_send, kwrest_arg_or_splat)
add_offense(kwrest_arg_or_splat, message: KWARGS_MSG) do |corrector|
add_parens_if_missing(def_arguments_or_send, corrector) if add_parens
corrector.replace(kwrest_arg_or_splat, '**')
end
end
def register_forward_block_arg_offense(add_parens, def_arguments_or_send, block_arg)
return if target_ruby_version <= 3.0 ||
block_arg.nil? || block_arg.source == '&' || explicit_block_name?
add_offense(block_arg, message: BLOCK_MSG) do |corrector|
add_parens_if_missing(def_arguments_or_send, corrector) if add_parens
corrector.replace(block_arg, '&')
end
end
def register_forward_all_offense(def_or_send, send_or_arguments, rest_or_splat)
arg_range = arguments_range(def_or_send, rest_or_splat)
add_offense(arg_range, message: FORWARDING_MSG) do |corrector|
add_parens_if_missing(send_or_arguments, corrector)
corrector.replace(arg_range, '...')
end
end
def arguments_range(node, first_node)
first_node.source_range.begin.join(node.last_argument.source_range.end)
end
def allow_only_rest_arguments?
cop_config.fetch('AllowOnlyRestArgument', true)
end
def use_anonymous_forwarding?
cop_config.fetch('UseAnonymousForwarding', false)
end
def add_parens_if_missing(node, corrector)
return if parentheses?(node)
return if node.send_type? && node.method?(:[])
add_parentheses(node, corrector)
end
# Classifies send nodes for possible rest/kwrest/all (including block) forwarding.
class SendNodeClassifier
extend NodePattern::Macros
# @!method forwarded_rest_arg?(node, rest_name)
def_node_matcher :forwarded_rest_arg?, '(splat (lvar %1))'
# @!method extract_forwarded_kwrest_arg(node, kwrest_name)
def_node_matcher :extract_forwarded_kwrest_arg, '(hash <$(kwsplat (lvar %1)) ...>)'
# @!method forwarded_block_arg?(node, block_name)
def_node_matcher :forwarded_block_arg?, '(block_pass {(lvar %1) nil?})'
# @!method def_all_anonymous_args?(node)
def_node_matcher :def_all_anonymous_args?, <<~PATTERN
(
def _
(args ... (restarg) (kwrestarg) (blockarg nil?))
_
)
PATTERN
# @!method send_all_anonymous_args?(node)
def_node_matcher :send_all_anonymous_args?, <<~PATTERN
(
send _ _
... (forwarded_restarg) (hash (forwarded_kwrestarg)) (block_pass nil?)
)
PATTERN
def initialize(def_node, send_node, referenced_lvars, forwardable_args, **config)
@def_node = def_node
@send_node = send_node
@referenced_lvars = referenced_lvars
@rest_arg, @kwrest_arg, @block_arg = *forwardable_args
@rest_arg_name, @kwrest_arg_name, @block_arg_name =
*forwardable_args.map { |a| a&.name }
@config = config
end
def forwarded_rest_arg
return nil if referenced_rest_arg?
arguments.find { |arg| forwarded_rest_arg?(arg, @rest_arg_name) }
end
def forwarded_kwrest_arg
return nil if referenced_kwrest_arg?
arguments.filter_map { |arg| extract_forwarded_kwrest_arg(arg, @kwrest_arg_name) }.first
end
def forwarded_block_arg
return nil if referenced_block_arg?
arguments.find { |arg| forwarded_block_arg?(arg, @block_arg_name) }
end
def classification
return nil unless forwarded_rest_arg || forwarded_kwrest_arg || forwarded_block_arg
if ruby_32_only_anonymous_forwarding?
:all_anonymous
elsif can_forward_all?
:all
else
:rest_or_kwrest
end
end
private
# rubocop:disable Metrics/CyclomaticComplexity
def can_forward_all?
return false if any_arg_referenced?
return false if ruby_30_or_lower_optarg?
return false if ruby_32_or_higher_missing_rest_or_kwest?
return false unless offensive_block_forwarding?
return false if additional_kwargs_or_forwarded_kwargs?
no_additional_args? || (target_ruby_version >= 3.0 && no_post_splat_args?)
end
# rubocop:enable Metrics/CyclomaticComplexity
# def foo(a = 41, ...) is a syntax error in 3.0.
def ruby_30_or_lower_optarg?
target_ruby_version <= 3.0 && @def_node.arguments.any?(&:optarg_type?)
end
def ruby_32_only_anonymous_forwarding?
# A block argument and an anonymous block argument are never passed together.
return false if @send_node.each_ancestor(:any_block).any?
def_all_anonymous_args?(@def_node) && send_all_anonymous_args?(@send_node)
end
def ruby_32_or_higher_missing_rest_or_kwest?
target_ruby_version >= 3.2 && !forwarded_rest_and_kwrest_args
end
def offensive_block_forwarding?
@block_arg ? forwarded_block_arg : allow_offense_for_no_block?
end
def forwarded_rest_and_kwrest_args
forwarded_rest_arg && forwarded_kwrest_arg
end
def arguments
@send_node.arguments
end
def referenced_rest_arg?
@referenced_lvars.include?(@rest_arg_name)
end
def referenced_kwrest_arg?
@referenced_lvars.include?(@kwrest_arg_name)
end
def referenced_block_arg?
@referenced_lvars.include?(@block_arg_name)
end
def any_arg_referenced?
referenced_rest_arg? || referenced_kwrest_arg? || referenced_block_arg?
end
def target_ruby_version
@config.fetch(:target_ruby_version)
end
def no_post_splat_args?
return true unless (splat_index = arguments.index(forwarded_rest_arg))
arg_after_splat = arguments[splat_index + 1]
[nil, :hash, :block_pass].include?(arg_after_splat&.type)
end
def additional_kwargs_or_forwarded_kwargs?
additional_kwargs? || forward_additional_kwargs?
end
def additional_kwargs?
@def_node.arguments.any? { |a| a.type?(:kwarg, :kwoptarg) }
end
def forward_additional_kwargs?
return false unless forwarded_kwrest_arg
!forwarded_kwrest_arg.parent.children.one?
end
def allow_offense_for_no_block?
!@config.fetch(:allow_only_rest_arguments)
end
def no_additional_args?
forwardable_count = [@rest_arg, @kwrest_arg, @block_arg].compact.size
return false if missing_rest_arg_or_kwrest_arg?
@def_node.arguments.size == forwardable_count &&
@send_node.arguments.size == forwardable_count
end
def missing_rest_arg_or_kwrest_arg?
(@rest_arg_name && !forwarded_rest_arg) ||
(@kwrest_arg_name && !forwarded_kwrest_arg)
end
end
def explicit_block_name?
config.for_enabled_cop('Naming/BlockForwarding')['EnforcedStyle'] == 'explicit'
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/collection_querying.rb | lib/rubocop/cop/style/collection_querying.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Prefer `Enumerable` predicate methods over expressions with `count`.
#
# The cop checks calls to `count` without arguments, or with a
# block. It doesn't register offenses for `count` with a positional
# argument because its behavior differs from predicate methods (`count`
# matches the argument using `==`, while `any?`, `none?` and `one?` use
# `===`).
#
# NOTE: This cop doesn't check `length` and `size` methods because they
# would yield false positives. For example, `String` implements `length`
# and `size`, but it doesn't include `Enumerable`.
#
# @safety
# The cop is unsafe because receiver might not include `Enumerable`, or
# it has nonstandard implementation of `count` or any replacement
# methods.
#
# It's also unsafe because for collections with falsey values, expressions
# with `count` without a block return a different result than methods `any?`,
# `none?` and `one?`:
#
# [source,ruby]
# ----
# [nil, false].count.positive?
# [nil].count == 1
# # => true
#
# [nil, false].any?
# [nil].one?
# # => false
#
# [nil].count == 0
# # => false
#
# [nil].none?
# # => true
# ----
#
# Autocorrection is unsafe when replacement methods don't iterate over
# every element in collection and the given block runs side effects:
#
# [source,ruby]
# ----
# x.count(&:method_with_side_effects).positive?
# # calls `method_with_side_effects` on every element
#
# x.any?(&:method_with_side_effects)
# # calls `method_with_side_effects` until first element returns a truthy value
# ----
#
# @example
#
# # bad
# x.count.positive?
# x.count > 0
# x.count != 0
#
# x.count(&:foo?).positive?
# x.count { |item| item.foo? }.positive?
#
# # good
# x.any?
#
# x.any?(&:foo?)
# x.any? { |item| item.foo? }
#
# # bad
# x.count.zero?
# x.count == 0
#
# # good
# x.none?
#
# # bad
# x.count == 1
# x.one?
#
# @example AllCops:ActiveSupportExtensionsEnabled: false (default)
#
# # good
# x.count > 1
#
# @example AllCops:ActiveSupportExtensionsEnabled: true
#
# # bad
# x.count > 1
#
# # good
# x.many?
#
class CollectionQuerying < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `%<prefer>s` instead.'
RESTRICT_ON_SEND = %i[positive? > != zero? ==].freeze
REPLACEMENTS = {
[:positive?, nil] => :any?,
[:>, 0] => :any?,
[:!=, 0] => :any?,
[:zero?, nil] => :none?,
[:==, 0] => :none?,
[:==, 1] => :one?,
[:>, 1] => :many?
}.freeze
# @!method count_predicate(node)
def_node_matcher :count_predicate, <<~PATTERN
(send
{
(any_block $(call !nil? :count) _ _)
$(call !nil? :count (block-pass _)?)
}
{
:positive? |
:> (int 0) |
:!= (int 0) |
:zero? |
:== (int 0) |
:== (int 1) |
:> (int 1)
})
PATTERN
def on_send(node)
return unless (count_node = count_predicate(node))
replacement_method = replacement_method(node)
return unless replacement_supported?(replacement_method)
offense_range = count_node.loc.selector.join(node.source_range.end)
add_offense(offense_range,
message: format(MSG, prefer: replacement_method)) do |corrector|
corrector.replace(count_node.loc.selector, replacement_method)
corrector.remove(removal_range(node))
end
end
private
def replacement_method(node)
REPLACEMENTS.fetch([node.method_name, node.first_argument&.value])
end
def replacement_supported?(method_name)
return true if active_support_extensions_enabled?
method_name != :many?
end
def removal_range(node)
range = (node.loc.dot || node.loc.selector).join(node.source_range.end)
range_with_surrounding_space(range, side: :left)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_current_directory_in_path.rb | lib/rubocop/cop/style/redundant_current_directory_in_path.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for paths given to `require_relative` that start with
# the current directory (`./`), which can be omitted.
#
# @example
#
# # bad
# require_relative './path/to/feature'
#
# # good
# require_relative 'path/to/feature'
#
class RedundantCurrentDirectoryInPath < Base
include RangeHelp
extend AutoCorrector
MSG = 'Remove the redundant current directory path.'
RESTRICT_ON_SEND = %i[require_relative].freeze
CURRENT_DIRECTORY_PREFIX = %r{\./+}.freeze
REDUNDANT_CURRENT_DIRECTORY_PREFIX = /\A#{CURRENT_DIRECTORY_PREFIX}/.freeze
def on_send(node)
return unless (first_argument = node.first_argument)
return unless (index = first_argument.source.index(CURRENT_DIRECTORY_PREFIX))
return unless (redundant_length = redundant_path_length(first_argument.str_content))
begin_pos = first_argument.source_range.begin.begin_pos + index
end_pos = begin_pos + redundant_length
range = range_between(begin_pos, end_pos)
add_offense(range) do |corrector|
corrector.remove(range)
end
end
private
def redundant_path_length(path)
return unless (match = path&.match(REDUNDANT_CURRENT_DIRECTORY_PREFIX))
match[0].length
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/if_unless_modifier.rb | lib/rubocop/cop/style/if_unless_modifier.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for `if` and `unless` statements that would fit on one line if
# written as modifier `if`/`unless`. The cop also checks for modifier
# `if`/`unless` lines that exceed the maximum line length.
#
# The maximum line length is configured in the `Layout/LineLength`
# cop. The tab size is configured in the `IndentationWidth` of the
# `Layout/IndentationStyle` cop.
#
# One-line pattern matching is always allowed. To ensure that there are few cases
# where the match variable is not used, and to prevent oversights. The variable `x`
# becomes undefined and raises `NameError` when the following example is changed to
# the modifier form:
#
# [source,ruby]
# ----
# if [42] in [x]
# x # `x` is undefined when using modifier form.
# end
# ----
#
# The code `def method_name = body if condition` is considered a bad case by
# `Style/AmbiguousEndlessMethodDefinition` cop. So, to respect the user's intention to use
# an endless method definition in the `if` body, the following code is allowed:
#
# [source,ruby]
# ----
# if condition
# def method_name = body
# end
# ----
#
# NOTE: It is allowed when `defined?` argument has an undefined value,
# because using the modifier form causes the following incompatibility:
#
# [source,ruby]
# ----
# unless defined?(undefined_foo)
# undefined_foo = 'default_value'
# end
# undefined_foo # => 'default_value'
#
# undefined_bar = 'default_value' unless defined?(undefined_bar)
# undefined_bar # => nil
# ----
#
# @example
# # bad
# if condition
# do_stuff(bar)
# end
#
# unless qux.empty?
# Foo.do_something
# end
#
# do_something_with_a_long_name(arg) if long_condition_that_prevents_code_fit_on_single_line
#
# # good
# do_stuff(bar) if condition
# Foo.do_something unless qux.empty?
#
# if long_condition_that_prevents_code_fit_on_single_line
# do_something_with_a_long_name(arg)
# end
#
# if short_condition # a long comment that makes it too long if it were just a single line
# do_something
# end
class IfUnlessModifier < Base
include StatementModifier
include LineLengthHelp
include AllowedPattern
include RangeHelp
include CommentsHelp
extend AutoCorrector
MSG_USE_MODIFIER = 'Favor modifier `%<keyword>s` usage when having a ' \
'single-line body. Another good alternative is ' \
'the usage of control flow `&&`/`||`.'
MSG_USE_NORMAL = 'Modifier form of `%<keyword>s` makes the line too long.'
def self.autocorrect_incompatible_with
[Style::SoleNestedConditional]
end
# rubocop:disable Metrics/AbcSize
def on_if(node)
return if endless_method?(node.body)
condition = node.condition
return if defined_nodes(condition).any? { |n| defined_argument_is_undefined?(node, n) } ||
pattern_matching_nodes(condition).any?
return unless (msg = message(node))
add_offense(node.loc.keyword, message: format(msg, keyword: node.keyword)) do |corrector|
next if part_of_ignored_node?(node)
autocorrect(corrector, node)
ignore_node(node)
end
end
# rubocop:enable Metrics/AbcSize
private
def endless_method?(body)
body&.any_def_type? && body.endless?
end
def defined_nodes(condition)
if condition.defined_type?
[condition]
else
condition.each_descendant.select(&:defined_type?)
end
end
def defined_argument_is_undefined?(if_node, defined_node)
defined_argument = defined_node.first_argument
return false unless defined_argument.type?(:lvar, :send)
if_node.left_siblings.none? do |sibling|
sibling.respond_to?(:lvasgn_type?) && sibling.lvasgn_type? &&
sibling.name == defined_argument.node_parts[0]
end
end
def pattern_matching_nodes(condition)
if condition.any_match_pattern_type?
[condition]
else
condition.each_descendant.select(&:any_match_pattern_type?)
end
end
def message(node)
if single_line_as_modifier?(node) && !named_capture_in_condition?(node)
MSG_USE_MODIFIER
elsif too_long_due_to_modifier?(node)
MSG_USE_NORMAL
end
end
def autocorrect(corrector, node)
replacement = if node.modifier_form?
replacement_for_modifier_form(corrector, node)
else
to_modifier_form(node)
end
corrector.replace(node, replacement)
end
def replacement_for_modifier_form(corrector, node) # rubocop:disable Metrics/AbcSize
comment = comment_on_node_line(node)
if comment && too_long_due_to_comment_after_modifier?(node, comment)
remove_comment(corrector, node, comment)
return to_modifier_form_with_move_comment(node, indent(node), comment)
end
last_argument = node.if_branch.last_argument if node.if_branch.send_type?
if last_argument.respond_to?(:heredoc?) && last_argument.heredoc?
heredoc = extract_heredoc_from(last_argument)
remove_heredoc(corrector, heredoc)
return to_normal_form_with_heredoc(node, indent(node), heredoc)
end
to_normal_form(node, indent(node))
end
def too_long_due_to_modifier?(node)
node.modifier_form? && too_long_single_line?(node) &&
!another_statement_on_same_line?(node)
end
def too_long_due_to_comment_after_modifier?(node, comment)
source_length = processed_source.lines[node.first_line - 1].length
max_line_length.between?(source_length - comment.source_range.length, source_length)
end
def allowed_patterns
line_length_config = config.for_cop('Layout/LineLength')
line_length_config['AllowedPatterns'] || line_length_config['IgnoredPatterns'] || []
end
def too_long_single_line?(node)
return false unless max_line_length
range = node.source_range
return false unless range.single_line?
return false unless line_length_enabled_at_line?(range.first_line)
line = range.source_line
return false if line_length(line) <= max_line_length
too_long_line_based_on_config?(range, line)
end
def too_long_line_based_on_config?(range, line)
return false if matches_allowed_pattern?(line)
too_long = too_long_line_based_on_allow_cop_directives?(range, line)
return too_long unless too_long == :undetermined
too_long_line_based_on_allow_uri?(line)
end
def too_long_line_based_on_allow_cop_directives?(range, line)
if allow_cop_directives? && directive_on_source_line?(range.line - 1)
return line_length_without_directive(line) > max_line_length
end
:undetermined
end
def too_long_line_based_on_allow_uri?(line)
if allow_uri?
uri_range = find_excessive_range(line, :uri)
return false if uri_range && allowed_position?(line, uri_range)
end
true
end
def too_long_line_based_on_allow_qualified_name?(line)
if allow_qualified_name?
namespace_range = find_excessive_range(line, :namespace)
return false if namespace_range && allowed_position?(line, namespace_range)
end
true
end
def line_length_enabled_at_line?(line)
processed_source.comment_config.cop_enabled_at_line?('Layout/LineLength', line)
end
def named_capture_in_condition?(node)
node.condition.match_with_lvasgn_type?
end
def non_eligible_node?(node)
non_simple_if_unless?(node) || node.chained? || node.nested_conditional? || super
end
def non_simple_if_unless?(node)
node.ternary? || node.elsif? || node.else?
end
def another_statement_on_same_line?(node)
line_no = node.source_range.last_line
# traverse the AST upwards until we find a 'begin' node
# we want to look at the following child and see if it is on the
# same line as this 'if' node
while node && !node.begin_type?
index = node.sibling_index
node = node.parent
end
node && (sibling = node.children[index + 1]) && sibling.source_range.first_line == line_no
end
def to_normal_form(node, indentation)
<<~RUBY.chomp
#{node.keyword} #{node.condition.source}
#{indentation} #{node.body.source}
#{indentation}end
RUBY
end
def to_normal_form_with_heredoc(node, indentation, heredoc)
heredoc_body, heredoc_end = heredoc
<<~RUBY.chomp
#{node.keyword} #{node.condition.source}
#{indentation} #{node.body.source}
#{indentation} #{heredoc_body.source.chomp}
#{indentation} #{heredoc_end.source.chomp}
#{indentation}end
RUBY
end
def to_modifier_form_with_move_comment(node, indentation, comment)
<<~RUBY.chomp
#{comment.source}
#{indentation}#{node.body.source} #{node.keyword} #{node.condition.source}
RUBY
end
def extract_heredoc_from(last_argument)
heredoc_body = last_argument.loc.heredoc_body
heredoc_end = last_argument.loc.heredoc_end
[heredoc_body, heredoc_end]
end
def remove_heredoc(corrector, heredoc)
heredoc.each do |range|
corrector.remove(range_by_whole_lines(range, include_final_newline: true))
end
end
def comment_on_node_line(node)
processed_source.comments.find { |c| same_line?(c, node) }
end
def remove_comment(corrector, _node, comment)
corrector.remove(range_with_surrounding_space(range: comment.source_range, side: :left))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/mixin_grouping.rb | lib/rubocop/cop/style/mixin_grouping.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for grouping of mixins in `class` and `module` bodies.
# By default it enforces mixins to be placed in separate declarations,
# but it can be configured to enforce grouping them in one declaration.
#
# @example EnforcedStyle: separated (default)
# # bad
# class Foo
# include Bar, Qox
# end
#
# # good
# class Foo
# include Qox
# include Bar
# end
#
# @example EnforcedStyle: grouped
# # bad
# class Foo
# extend Bar
# extend Qox
# end
#
# # good
# class Foo
# extend Qox, Bar
# end
class MixinGrouping < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MIXIN_METHODS = %i[extend include prepend].freeze
MSG = 'Put `%<mixin>s` mixins in %<suffix>s.'
def on_class(node)
begin_node = node.child_nodes.find(&:begin_type?) || node
begin_node.each_child_node(:send).select(&:macro?).each do |macro|
next if !MIXIN_METHODS.include?(macro.method_name) || macro.arguments.empty?
check(macro)
end
end
alias on_module on_class
private
def range_to_remove_for_subsequent_mixin(mixins, node)
range = node.source_range
prev_mixin = mixins.each_cons(2) { |m, n| break m if n == node }
between = prev_mixin.source_range.end.join(range.begin)
# if separated from previous mixin with only whitespace?
unless /\S/.match?(between.source)
range = range.join(between) # then remove that too
end
range
end
def check(send_node)
if separated_style?
check_separated_style(send_node)
else
check_grouped_style(send_node)
end
end
def check_grouped_style(send_node)
return if sibling_mixins(send_node).size == 1
message = format(MSG, mixin: send_node.method_name, suffix: 'a single statement')
add_offense(send_node, message: message) do |corrector|
range = send_node.source_range
mixins = sibling_mixins(send_node)
if send_node == mixins.first
correction = group_mixins(send_node, mixins)
else
range = range_to_remove_for_subsequent_mixin(mixins, send_node)
correction = ''
end
corrector.replace(range, correction)
end
end
def check_separated_style(send_node)
return if send_node.arguments.one?
message = format(MSG, mixin: send_node.method_name, suffix: 'separate statements')
add_offense(send_node, message: message) do |corrector|
range = send_node.source_range
correction = separate_mixins(send_node)
corrector.replace(range, correction)
end
end
def sibling_mixins(send_node)
siblings = send_node.parent.each_child_node(:send).select(&:macro?)
siblings.select { |sibling_node| sibling_node.method?(send_node.method_name) }
end
def grouped_style?
style == :grouped
end
def separated_style?
style == :separated
end
def separate_mixins(node)
arguments = node.arguments.reverse
mixins = ["#{node.method_name} #{arguments.first.source}"]
arguments[1..].inject(mixins) do |replacement, arg|
replacement << "#{indent(node)}#{node.method_name} #{arg.source}"
end.join("\n")
end
def group_mixins(node, mixins)
mixin_names = mixins.reverse.flat_map { |mixin| mixin.arguments.map(&:source) }
"#{node.method_name} #{mixin_names.join(', ')}"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/magic_comment_format.rb | lib/rubocop/cop/style/magic_comment_format.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Ensures magic comments are written consistently throughout your code base.
# Looks for discrepancies in separators (`-` vs `_`) and capitalization for
# both magic comment directives and values.
#
# Required capitalization can be set with the `DirectiveCapitalization` and
# `ValueCapitalization` configuration keys.
#
# NOTE: If one of these configuration is set to nil, any capitalization is allowed.
#
# @example EnforcedStyle: snake_case (default)
# # The `snake_case` style will enforce that the frozen string literal
# # comment is written in snake case. (Words separated by underscores)
# # bad
# # frozen-string-literal: true
#
# module Bar
# # ...
# end
#
# # good
# # frozen_string_literal: false
#
# module Bar
# # ...
# end
#
# @example EnforcedStyle: kebab_case
# # The `kebab_case` style will enforce that the frozen string literal
# # comment is written in kebab case. (Words separated by hyphens)
# # bad
# # frozen_string_literal: true
#
# module Baz
# # ...
# end
#
# # good
# # frozen-string-literal: true
#
# module Baz
# # ...
# end
#
# @example DirectiveCapitalization: lowercase (default)
# # bad
# # FROZEN-STRING-LITERAL: true
#
# # good
# # frozen-string-literal: true
#
# @example DirectiveCapitalization: uppercase
# # bad
# # frozen-string-literal: true
#
# # good
# # FROZEN-STRING-LITERAL: true
#
# @example DirectiveCapitalization: nil
# # any capitalization is accepted
#
# # good
# # frozen-string-literal: true
#
# # good
# # FROZEN-STRING-LITERAL: true
#
# @example ValueCapitalization: nil (default)
# # any capitalization is accepted
#
# # good
# # frozen-string-literal: true
#
# # good
# # frozen-string-literal: TRUE
#
# @example ValueCapitalization: lowercase
# # when a value is not given, any capitalization is accepted
#
# # bad
# # frozen-string-literal: TRUE
#
# # good
# # frozen-string-literal: TRUE
#
# @example ValueCapitalization: uppercase
# # bad
# # frozen-string-literal: true
#
# # good
# # frozen-string-literal: TRUE
#
class MagicCommentFormat < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
SNAKE_SEPARATOR = '_'
KEBAB_SEPARATOR = '-'
MSG = 'Prefer %<style>s case for magic comments.'
MSG_VALUE = 'Prefer %<case>s for magic comment values.'
# Value object to extract source ranges for the different parts of a magic comment
class CommentRange
extend SimpleForwardable
DIRECTIVE_REGEXP = Regexp.union(MagicComment::KEYWORDS.map do |_, v|
Regexp.new(v, Regexp::IGNORECASE)
end).freeze
VALUE_REGEXP = Regexp.new("(?:#{DIRECTIVE_REGEXP}:\s*)(.*?)(?=;|$)")
def_delegators :@comment, :text, :loc
attr_reader :comment
def initialize(comment)
@comment = comment
end
# A magic comment can contain one directive (normal style) or
# multiple directives (emacs style)
def directives
@directives ||= begin
matches = []
text.scan(DIRECTIVE_REGEXP) do
offset = Regexp.last_match.offset(0)
matches << loc.expression.adjust(begin_pos: offset.first)
.with(end_pos: loc.expression.begin_pos + offset.last)
end
matches
end
end
# A magic comment can contain one value (normal style) or
# multiple directives (emacs style)
def values
@values ||= begin
matches = []
text.scan(VALUE_REGEXP) do
offset = Regexp.last_match.offset(1)
matches << loc.expression.adjust(begin_pos: offset.first)
.with(end_pos: loc.expression.begin_pos + offset.last)
end
matches
end
end
end
def on_new_investigation
return unless processed_source.ast
magic_comments.each do |comment|
issues = find_issues(comment)
register_offenses(issues) if issues.any?
end
end
private
def magic_comments
processed_source.each_comment_in_lines(leading_comment_lines)
.select { |comment| MagicComment.parse(comment.text).valid? }
.map { |comment| CommentRange.new(comment) }
end
def leading_comment_lines
first_non_comment_token = processed_source.tokens.find { |token| !token.comment? }
if first_non_comment_token
0...first_non_comment_token.line
else
(0..)
end
end
def find_issues(comment)
issues = { directives: [], values: [] }
comment.directives.each do |directive|
issues[:directives] << directive if directive_offends?(directive)
end
comment.values.each do |value| # rubocop:disable Style/HashEachMethods
issues[:values] << value if wrong_capitalization?(value.source, value_capitalization)
end
issues
end
def directive_offends?(directive)
incorrect_separator?(directive.source) ||
wrong_capitalization?(directive.source, directive_capitalization)
end
def register_offenses(issues)
fix_directives(issues[:directives])
fix_values(issues[:values])
end
def fix_directives(issues)
return if issues.empty?
msg = format(MSG, style: expected_style)
issues.each do |directive|
add_offense(directive, message: msg) do |corrector|
replacement = replace_separator(replace_capitalization(directive.source,
directive_capitalization))
corrector.replace(directive, replacement)
end
end
end
def fix_values(issues)
return if issues.empty?
msg = format(MSG_VALUE, case: value_capitalization)
issues.each do |value|
add_offense(value, message: msg) do |corrector|
corrector.replace(value, replace_capitalization(value.source, value_capitalization))
end
end
end
def expected_style
[directive_capitalization, style].compact.join(' ').gsub(/_?case\b/, '')
end
def wrong_separator
style == :snake_case ? KEBAB_SEPARATOR : SNAKE_SEPARATOR
end
def correct_separator
style == :snake_case ? SNAKE_SEPARATOR : KEBAB_SEPARATOR
end
def incorrect_separator?(text)
text[wrong_separator]
end
def wrong_capitalization?(text, expected_case)
return false unless expected_case
case expected_case
when :lowercase
text != text.downcase
when :uppercase
text != text.upcase
end
end
def replace_separator(text)
text.tr(wrong_separator, correct_separator)
end
def replace_capitalization(text, style)
return text unless style
case style
when :lowercase
text.downcase
when :uppercase
text.upcase
end
end
def line_range(line)
processed_source.buffer.line_range(line)
end
def directive_capitalization
cop_config['DirectiveCapitalization']&.to_sym.tap do |style|
unless valid_capitalization?(style)
raise "Unknown `DirectiveCapitalization` #{style} selected!"
end
end
end
def value_capitalization
cop_config['ValueCapitalization']&.to_sym.tap do |style|
unless valid_capitalization?(style)
raise "Unknown `ValueCapitalization` #{style} selected!"
end
end
end
def valid_capitalization?(style)
return true unless style
supported_capitalizations.include?(style)
end
def supported_capitalizations
cop_config['SupportedCapitalizations'].map(&:to_sym)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/string_hash_keys.rb | lib/rubocop/cop/style/string_hash_keys.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the use of strings as keys in hashes. The use of
# symbols is preferred instead.
#
# @safety
# This cop is unsafe because while symbols are preferred for hash keys,
# there are instances when string keys are required.
#
# @example
# # bad
# { 'one' => 1, 'two' => 2, 'three' => 3 }
#
# # good
# { one: 1, two: 2, three: 3 }
class StringHashKeys < Base
extend AutoCorrector
MSG = 'Prefer symbols instead of strings as hash keys.'
# @!method string_hash_key?(node)
def_node_matcher :string_hash_key?, <<~PATTERN
(pair (str _) _)
PATTERN
# @!method receive_environments_method?(node)
def_node_matcher :receive_environments_method?, <<~PATTERN
{
^^(send (const {nil? cbase} :IO) :popen ...)
^^(send (const {nil? cbase} :Open3)
{:capture2 :capture2e :capture3 :popen2 :popen2e :popen3} ...)
^^^(send (const {nil? cbase} :Open3)
{:pipeline :pipeline_r :pipeline_rw :pipeline_start :pipeline_w} ...)
^^(send {nil? (const {nil? cbase} :Kernel)} {:spawn :system} ...)
^^(send _ {:gsub :gsub!} ...)
}
PATTERN
def on_pair(node)
return unless string_hash_key?(node)
key_content = node.key.str_content
return unless key_content.valid_encoding?
return if receive_environments_method?(node)
add_offense(node.key) do |corrector|
symbol_content = key_content.to_sym.inspect
corrector.replace(node.key, symbol_content)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/exponential_notation.rb | lib/rubocop/cop/style/exponential_notation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces consistency when using exponential notation
# for numbers in the code (eg 1.2e4). Different styles are supported:
#
# * `scientific` which enforces a mantissa between 1 (inclusive) and 10 (exclusive).
# * `engineering` which enforces the exponent to be a multiple of 3 and the mantissa
# to be between 0.1 (inclusive) and 1000 (exclusive).
# * `integral` which enforces the mantissa to always be a whole number without
# trailing zeroes.
#
# @example EnforcedStyle: scientific (default)
# # Enforces a mantissa between 1 (inclusive) and 10 (exclusive).
#
# # bad
# 10e6
# 0.3e4
# 11.7e5
# 3.14e0
#
# # good
# 1e7
# 3e3
# 1.17e6
# 3.14
#
# @example EnforcedStyle: engineering
# # Enforces using multiple of 3 exponents,
# # mantissa should be between 0.1 (inclusive) and 1000 (exclusive)
#
# # bad
# 3.2e7
# 0.1e5
# 12e5
# 1232e6
#
# # good
# 32e6
# 10e3
# 1.2e6
# 1.232e9
#
# @example EnforcedStyle: integral
# # Enforces the mantissa to have no decimal part and no
# # trailing zeroes.
#
# # bad
# 3.2e7
# 0.1e5
# 120e4
#
# # good
# 32e6
# 1e4
# 12e5
#
class ExponentialNotation < Base
include ConfigurableEnforcedStyle
MESSAGES = {
scientific: 'Use a mantissa >= 1 and < 10.',
engineering: 'Use an exponent divisible by 3 and a mantissa >= 0.1 and < 1000.',
integral: 'Use an integer as mantissa, without trailing zero.'
}.freeze
def on_float(node)
add_offense(node) if offense?(node)
end
private
def scientific?(node)
mantissa, = node.source.split('e')
/^-?[1-9](\.\d*[0-9])?$/.match?(mantissa)
end
def engineering?(node)
mantissa, exponent = node.source.split('e')
return false unless /^-?\d+$/.match?(exponent)
return false unless (exponent.to_i % 3).zero?
return false if /^-?\d{4}/.match?(mantissa)
return false if /^-?0\d/.match?(mantissa)
return false if /^-?0.0/.match?(mantissa)
true
end
def integral?(node)
mantissa, = node.source.split('e')
/^-?[1-9](\d*[1-9])?$/.match?(mantissa)
end
def offense?(node)
return false unless node.source['e']
case style
when :scientific
!scientific?(node)
when :engineering
!engineering?(node)
when :integral
!integral?(node)
else
false
end
end
def message(_node)
MESSAGES[style]
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/multiline_ternary_operator.rb | lib/rubocop/cop/style/multiline_ternary_operator.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for multi-line ternary op expressions.
#
# NOTE: `return if ... else ... end` is syntax error. If `return` is used before
# multiline ternary operator expression, it will be autocorrected to single-line
# ternary operator. The same is true for `break`, `next`, and method call.
#
# @example
# # bad
# a = cond ?
# b : c
# a = cond ? b :
# c
# a = cond ?
# b :
# c
#
# return cond ?
# b :
# c
#
# # good
# a = cond ? b : c
# a = if cond
# b
# else
# c
# end
#
# return cond ? b : c
#
class MultilineTernaryOperator < Base
include CommentsHelp
extend AutoCorrector
MSG_IF = 'Avoid multi-line ternary operators, use `if` or `unless` instead.'
MSG_SINGLE_LINE = 'Avoid multi-line ternary operators, use single-line instead.'
SINGLE_LINE_TYPES = %i[return break next send csend].freeze
def on_if(node)
return unless offense?(node)
message = enforce_single_line_ternary_operator?(node) ? MSG_SINGLE_LINE : MSG_IF
add_offense(node, message: message) do |corrector|
next if part_of_ignored_node?(node)
autocorrect(corrector, node)
ignore_node(node)
end
end
private
def offense?(node)
node.ternary? && node.multiline? && node.source != replacement(node)
end
def autocorrect(corrector, node)
corrector.replace(node, replacement(node))
return unless (parent = node.parent)
return unless (comments_in_condition = comments_in_condition(node))
corrector.insert_before(parent, comments_in_condition)
end
def replacement(node)
if enforce_single_line_ternary_operator?(node)
"#{node.condition.source} ? #{node.if_branch.source} : #{node.else_branch.source}"
else
<<~RUBY.chop
if #{node.condition.source}
#{node.if_branch.source}
else
#{node.else_branch.source}
end
RUBY
end
end
def comments_in_condition(node)
comments_in_range(node).map do |comment|
"#{comment.source}\n"
end.join
end
def enforce_single_line_ternary_operator?(node)
SINGLE_LINE_TYPES.include?(node.parent&.type) && !use_assignment_method?(node.parent)
end
def use_assignment_method?(node)
node.send_type? && node.assignment_method?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/identical_conditional_branches.rb | lib/rubocop/cop/style/identical_conditional_branches.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for identical expressions at the beginning or end of
# each branch of a conditional expression. Such expressions should normally
# be placed outside the conditional expression - before or after it.
#
# NOTE: The cop is poorly named and some people might think that it actually
# checks for duplicated conditional branches. The name will probably be changed
# in a future major RuboCop release.
#
# @safety
# Autocorrection is unsafe because changing the order of method invocations
# may change the behavior of the code. For example:
#
# [source,ruby]
# ----
# if method_that_modifies_global_state # 1
# method_that_relies_on_global_state # 2
# foo # 3
# else
# method_that_relies_on_global_state # 2
# bar # 3
# end
# ----
#
# In this example, `method_that_relies_on_global_state` will be moved before
# `method_that_modifies_global_state`, which changes the behavior of the program.
#
# @example
# # bad
# if condition
# do_x
# do_z
# else
# do_y
# do_z
# end
#
# # good
# if condition
# do_x
# else
# do_y
# end
# do_z
#
# # bad
# if condition
# do_z
# do_x
# else
# do_z
# do_y
# end
#
# # good
# do_z
# if condition
# do_x
# else
# do_y
# end
#
# # bad
# case foo
# when 1
# do_x
# when 2
# do_x
# else
# do_x
# end
#
# # good
# case foo
# when 1
# do_x
# do_y
# when 2
# # nothing
# else
# do_x
# do_z
# end
#
# # bad
# case foo
# in 1
# do_x
# in 2
# do_x
# else
# do_x
# end
#
# # good
# case foo
# in 1
# do_x
# do_y
# in 2
# # nothing
# else
# do_x
# do_z
# end
class IdenticalConditionalBranches < Base
include RangeHelp
extend AutoCorrector
MSG = 'Move `%<source>s` out of the conditional.'
def on_if(node)
return if node.elsif?
branches = expand_elses(node.else_branch).unshift(node.if_branch)
check_branches(node, branches)
end
def on_case(node)
return unless node.else? && node.else_branch
branches = node.when_branches.map(&:body).push(node.else_branch)
check_branches(node, branches)
end
def on_case_match(node)
return unless node.else? && node.else_branch
branches = node.in_pattern_branches.map(&:body).push(node.else_branch)
check_branches(node, branches)
end
private
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def check_branches(node, branches)
# return if any branch is empty. An empty branch can be an `if`
# without an `else` or a branch that contains only comments.
return if branches.any?(&:nil?)
tails = branches.map { |branch| tail(branch) }
check_expressions(node, tails, :after_condition) if duplicated_expressions?(node, tails)
return if last_child_of_parent?(node) &&
branches.any? { |branch| single_child_branch?(branch) }
heads = branches.map { |branch| head(branch) }
return unless duplicated_expressions?(node, heads)
condition_variable = assignable_condition_value(node)
head = heads.first
if head.respond_to?(:assignment?) && head.assignment?
# The `send` node is used instead of the `indexasgn` node, so `name` cannot be used.
# https://github.com/rubocop/rubocop-ast/blob/v1.29.0/lib/rubocop/ast/node/indexasgn_node.rb
#
# FIXME: It would be better to update `RuboCop::AST::OpAsgnNode` or its subclasses to
# handle `self.foo ||= value` as a solution, instead of using `head.node_parts[0].to_s`.
assigned_value = head.send_type? ? head.receiver.source : head.node_parts[0].to_s
return if condition_variable == assigned_value
end
check_expressions(node, heads, :before_condition)
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def duplicated_expressions?(node, expressions)
unique_expressions = expressions.uniq
return false unless expressions.size >= 1 && unique_expressions.one?
unique_expression = unique_expressions.first
return true unless unique_expression&.assignment?
lhs = unique_expression.child_nodes.first
node.condition.child_nodes.none? { |n| n.source == lhs.source if n.variable? }
end
def assignable_condition_value(node)
if node.condition.call_type?
(receiver = node.condition.receiver) ? receiver.source : node.condition.source
elsif node.condition.variable?
node.condition.source
end
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
def check_expressions(node, expressions, insert_position)
return if expressions.any?(&:nil?)
inserted_expression = false
expressions.each do |expression|
add_offense(expression) do |corrector|
next if node.if_type? && (node.ternary? || node.then?)
range = range_by_whole_lines(expression.source_range, include_final_newline: true)
corrector.remove(range)
next if inserted_expression
if node.parent&.assignment?
correct_assignment(corrector, node, expression, insert_position)
else
correct_no_assignment(corrector, node, expression, insert_position)
end
inserted_expression = true
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
def correct_assignment(corrector, node, expression, insert_position)
if insert_position == :after_condition
assignment = node.parent.source_range.with(end_pos: node.source_range.begin_pos)
corrector.remove(assignment)
corrector.insert_after(node, "\n#{assignment.source}#{expression.source}")
else
corrector.insert_before(node.parent, "#{expression.source}\n")
end
end
def correct_no_assignment(corrector, node, expression, insert_position)
if insert_position == :after_condition
corrector.insert_after(node, "\n#{expression.source}")
else
corrector.insert_before(node, "#{expression.source}\n")
end
end
def last_child_of_parent?(node)
return true unless (parent = node.parent)
parent.child_nodes.last == node
end
def single_child_branch?(branch_node)
!branch_node.begin_type? || branch_node.children.size == 1
end
def message(node)
format(MSG, source: node.source)
end
# `elsif` branches show up in the if node as nested `else` branches. We
# need to recursively iterate over all `else` branches.
def expand_elses(branch)
if branch.nil?
[nil]
elsif branch.if_type?
_condition, elsif_branch, else_branch = *branch
expand_elses(else_branch).unshift(elsif_branch)
else
[branch]
end
end
def tail(node)
node.begin_type? ? node.children.last : node
end
def head(node)
node.begin_type? ? node.children.first : node
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/rescue_standard_error.rb | lib/rubocop/cop/style/rescue_standard_error.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for rescuing `StandardError`. There are two supported
# styles `implicit` and `explicit`. This cop will not register an offense
# if any error other than `StandardError` is specified.
#
# @example EnforcedStyle: explicit (default)
# # `explicit` will enforce using `rescue StandardError`
# # instead of `rescue`.
#
# # bad
# begin
# foo
# rescue
# bar
# end
#
# # good
# begin
# foo
# rescue StandardError
# bar
# end
#
# # good
# begin
# foo
# rescue OtherError
# bar
# end
#
# # good
# begin
# foo
# rescue StandardError, SecurityError
# bar
# end
#
# @example EnforcedStyle: implicit
# # `implicit` will enforce using `rescue` instead of
# # `rescue StandardError`.
#
# # bad
# begin
# foo
# rescue StandardError
# bar
# end
#
# # good
# begin
# foo
# rescue
# bar
# end
#
# # good
# begin
# foo
# rescue OtherError
# bar
# end
#
# # good
# begin
# foo
# rescue StandardError, SecurityError
# bar
# end
class RescueStandardError < Base
include RescueNode
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG_IMPLICIT = 'Omit the error class when rescuing `StandardError` by itself.'
MSG_EXPLICIT = 'Avoid rescuing without specifying an error class.'
# @!method rescue_without_error_class?(node)
def_node_matcher :rescue_without_error_class?, <<~PATTERN
(resbody nil? _ _)
PATTERN
# @!method rescue_standard_error?(node)
def_node_matcher :rescue_standard_error?, <<~PATTERN
(resbody $(array (const {nil? cbase} :StandardError)) _ _)
PATTERN
def on_resbody(node)
return if rescue_modifier?(node)
case style
when :implicit
rescue_standard_error?(node) do |error|
offense_for_implicit_enforced_style(node, error)
end
when :explicit
rescue_without_error_class?(node) { offense_for_explicit_enforced_style(node) }
end
end
private
def offense_for_implicit_enforced_style(node, error)
range = node.loc.keyword.join(error.source_range)
add_offense(range, message: MSG_IMPLICIT) do |corrector|
error = rescue_standard_error?(node)
range = range_between(node.loc.keyword.end_pos, error.source_range.end_pos)
corrector.remove(range)
end
end
def offense_for_explicit_enforced_style(node)
add_offense(node.loc.keyword, message: MSG_EXPLICIT) do |corrector|
corrector.insert_after(node.loc.keyword, ' StandardError')
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/nested_parenthesized_calls.rb | lib/rubocop/cop/style/nested_parenthesized_calls.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for unparenthesized method calls in the argument list
# of a parenthesized method call.
# `be`, `be_a`, `be_an`, `be_between`, `be_falsey`, `be_kind_of`, `be_instance_of`,
# `be_truthy`, `be_within`, `eq`, `eql`, `end_with`, `include`, `match`, `raise_error`,
# `respond_to`, and `start_with` methods are allowed by default.
# These are customizable with `AllowedMethods` option.
#
# @example
# # good
# method1(method2(arg))
#
# # bad
# method1(method2 arg)
#
# @example AllowedMethods: [foo]
# # good
# method1(foo arg)
#
class NestedParenthesizedCalls < Base
include RangeHelp
include AllowedMethods
extend AutoCorrector
MSG = 'Add parentheses to nested method call `%<source>s`.'
def self.autocorrect_incompatible_with
[Style::MethodCallWithArgsParentheses]
end
def on_send(node)
return unless node.parenthesized?
node.each_child_node(:call) do |nested|
next if allowed_omission?(nested)
message = format(MSG, source: nested.source)
add_offense(nested, message: message) do |corrector|
autocorrect(corrector, nested)
end
end
end
alias on_csend on_send
private
def autocorrect(corrector, nested)
first_arg = nested.first_argument.source_range
last_arg = nested.last_argument.source_range
leading_space =
range_with_surrounding_space(first_arg.begin,
side: :left,
whitespace: true,
continuations: true)
corrector.replace(leading_space, '(')
corrector.insert_after(last_arg, ')')
end
def allowed_omission?(send_node)
!send_node.arguments? || send_node.parenthesized? ||
send_node.setter_method? || send_node.operator_method? ||
allowed?(send_node)
end
def allowed?(send_node)
send_node.parent.arguments.one? &&
allowed_method?(send_node.method_name) &&
send_node.arguments.one?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/empty_else.rb | lib/rubocop/cop/style/empty_else.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for empty else-clauses, possibly including comments and/or an
# explicit `nil` depending on the EnforcedStyle.
#
# @example EnforcedStyle: both (default)
# # warn on empty else and else with nil in it
#
# # bad
# if condition
# statement
# else
# nil
# end
#
# # bad
# if condition
# statement
# else
# end
#
# # good
# if condition
# statement
# else
# statement
# end
#
# # good
# if condition
# statement
# end
#
# @example EnforcedStyle: empty
# # warn only on empty else
#
# # bad
# if condition
# statement
# else
# end
#
# # good
# if condition
# statement
# else
# nil
# end
#
# # good
# if condition
# statement
# else
# statement
# end
#
# # good
# if condition
# statement
# end
#
# @example EnforcedStyle: nil
# # warn on else with nil in it
#
# # bad
# if condition
# statement
# else
# nil
# end
#
# # good
# if condition
# statement
# else
# end
#
# # good
# if condition
# statement
# else
# statement
# end
#
# # good
# if condition
# statement
# end
#
# @example AllowComments: false (default)
#
# # bad
# if condition
# statement
# else
# # something comment
# nil
# end
#
# # bad
# if condition
# statement
# else
# # something comment
# end
#
# @example AllowComments: true
#
# # good
# if condition
# statement
# else
# # something comment
# nil
# end
#
# # good
# if condition
# statement
# else
# # something comment
# end
#
class EmptyElse < Base
include OnNormalIfUnless
include ConfigurableEnforcedStyle
include RangeHelp
extend AutoCorrector
MSG = 'Redundant `else`-clause.'
NIL_STYLES = %i[nil both].freeze
EMPTY_STYLES = %i[empty both].freeze
def on_normal_if_unless(node)
check(node)
end
def on_case(node)
check(node)
end
private
def check(node)
return if cop_config['AllowComments'] && comment_in_else?(node)
empty_check(node) if empty_style?
nil_check(node) if nil_style?
end
def nil_style?
NIL_STYLES.include?(style)
end
def empty_style?
EMPTY_STYLES.include?(style)
end
def empty_check(node)
return unless node.else? && !node.else_branch
add_offense(node.loc.else) { |corrector| autocorrect(corrector, node) }
end
def nil_check(node)
return unless node.else_branch&.nil_type?
add_offense(node.loc.else) { |corrector| autocorrect(corrector, node) }
end
def autocorrect(corrector, node)
return false if autocorrect_forbidden?(node.type.to_s)
return false if comment_in_else?(node)
end_pos = base_node(node).loc.end.begin_pos
corrector.remove(range_between(node.loc.else.begin_pos, end_pos))
end
def comment_in_else?(node)
node = node.parent while node.if_type? && node.elsif?
return false unless node.else?
processed_source.contains_comment?(node.loc.else.join(node.source_range.end))
end
def base_node(node)
return node if node.case_type?
return node unless node.elsif?
node.each_ancestor(:if, :case, :when).find(-> { node }) { |parent| parent.loc.end }
end
def autocorrect_forbidden?(type)
[type, 'both'].include?(missing_else_style)
end
def missing_else_style
missing_cfg = config.for_cop('Style/MissingElse')
missing_cfg.fetch('Enabled') ? missing_cfg['EnforcedStyle'] : nil
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/percent_q_literals.rb | lib/rubocop/cop/style/percent_q_literals.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for usage of the %Q() syntax when %q() would do.
#
# @example EnforcedStyle: lower_case_q (default)
# # The `lower_case_q` style prefers `%q` unless
# # interpolation is needed.
# # bad
# %Q[Mix the foo into the baz.]
# %Q(They all said: 'Hooray!')
#
# # good
# %q[Mix the foo into the baz]
# %q(They all said: 'Hooray!')
#
# @example EnforcedStyle: upper_case_q
# # The `upper_case_q` style requires the sole use of `%Q`.
# # bad
# %q/Mix the foo into the baz./
# %q{They all said: 'Hooray!'}
#
# # good
# %Q/Mix the foo into the baz./
# %Q{They all said: 'Hooray!'}
class PercentQLiterals < Base
include PercentLiteral
include ConfigurableEnforcedStyle
extend AutoCorrector
LOWER_CASE_Q_MSG = 'Do not use `%Q` unless interpolation is needed. Use `%q`.'
UPPER_CASE_Q_MSG = 'Use `%Q` instead of `%q`.'
def on_str(node)
process(node, '%Q', '%q')
end
private
def on_percent_literal(node)
return if correct_literal_style?(node)
# Report offense only if changing case doesn't change semantics,
# i.e., if the string would become dynamic or has special characters.
ast = parse(corrected(node.source)).ast
return if node.children != ast&.children
add_offense(node.loc.begin) do |corrector|
corrector.replace(node, corrected(node.source))
end
end
def correct_literal_style?(node)
(style == :lower_case_q && type(node) == '%q') ||
(style == :upper_case_q && type(node) == '%Q')
end
def message(_range)
style == :lower_case_q ? LOWER_CASE_Q_MSG : UPPER_CASE_Q_MSG
end
def corrected(src)
src.sub(src[1], src[1].swapcase)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/empty_literal.rb | lib/rubocop/cop/style/empty_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the use of a method, the result of which
# would be a literal, like an empty array, hash, or string.
#
# NOTE: When frozen string literals are enabled, `String.new`
# isn't corrected to an empty string since the former is
# mutable and the latter would be frozen.
#
# @example
# # bad
# a = Array.new
# a = Array[]
# h = Hash.new
# h = Hash[]
# s = String.new
#
# # good
# a = []
# h = {}
# s = ''
class EmptyLiteral < Base
include FrozenStringLiteral
include RangeHelp
include StringLiteralsHelp
extend AutoCorrector
ARR_MSG = 'Use array literal `[]` instead of `%<current>s`.'
HASH_MSG = 'Use hash literal `{}` instead of `%<current>s`.'
STR_MSG = 'Use string literal `%<prefer>s` instead of `String.new`.'
RESTRICT_ON_SEND = %i[new [] Array Hash].freeze
# @!method array_node(node)
def_node_matcher :array_node, '(send (const {nil? cbase} :Array) :new (array)?)'
# @!method hash_node(node)
def_node_matcher :hash_node, '(send (const {nil? cbase} :Hash) :new)'
# @!method str_node(node)
def_node_matcher :str_node, '(send (const {nil? cbase} :String) :new)'
# @!method array_with_block(node)
def_node_matcher :array_with_block, '(block (send (const {nil? cbase} :Array) :new) args _)'
# @!method hash_with_block(node)
def_node_matcher :hash_with_block, <<~PATTERN
{
(block (send (const {nil? cbase} :Hash) :new) args _)
(numblock (send (const {nil? cbase} :Hash) :new) ...)
}
PATTERN
# @!method array_with_index(node)
def_node_matcher :array_with_index, <<~PATTERN
{
(send (const {nil? cbase} :Array) :[])
(send nil? :Array (array))
}
PATTERN
# @!method hash_with_index(node)
def_node_matcher :hash_with_index, <<~PATTERN
{
(send (const {nil? cbase} :Hash) :[])
(send nil? :Hash (array))
}
PATTERN
def on_send(node)
return unless (message = offense_message(node))
add_offense(node, message: message) do |corrector|
corrector.replace(replacement_range(node), correction(node))
end
end
private
def offense_message(node)
if offense_array_node?(node)
format(ARR_MSG, current: node.source)
elsif offense_hash_node?(node)
format(HASH_MSG, current: node.source)
elsif str_node(node) && !frozen_strings?
format(STR_MSG, prefer: preferred_string_literal)
end
end
def first_argument_unparenthesized?(node)
parent = node.parent
return false unless parent && %i[send super zsuper].include?(parent.type)
node.equal?(parent.first_argument) && !parentheses?(node.parent)
end
def replacement_range(node)
if hash_node(node) && first_argument_unparenthesized?(node)
# `some_method {}` is not same as `some_method Hash.new`
# because the braces are interpreted as a block. We will have
# to rewrite the arguments to wrap them in parenthesis.
args = node.parent.arguments
range_between(args[0].source_range.begin_pos - 1, args[-1].source_range.end_pos)
else
node.source_range
end
end
def offense_array_node?(node)
(array_node(node) && !array_with_block(node.parent)) || array_with_index(node)
end
def offense_hash_node?(node)
# If Hash.new takes a block, it can't be changed to {}.
(hash_node(node) && !hash_with_block(node.parent)) || hash_with_index(node)
end
def correction(node)
if offense_array_node?(node)
'[]'
elsif str_node(node)
preferred_string_literal
elsif offense_hash_node?(node)
if first_argument_unparenthesized?(node)
# `some_method {}` is not same as `some_method Hash.new`
# because the braces are interpreted as a block. We will have
# to rewrite the arguments to wrap them in parenthesis.
args = node.parent.arguments
"(#{args[1..].map(&:source).unshift('{}').join(', ')})"
else
'{}'
end
end
end
def frozen_strings?
return true if frozen_string_literals_enabled?
frozen_string_cop_enabled = config.cop_enabled?('Style/FrozenStringLiteralComment')
frozen_string_cop_enabled &&
!frozen_string_literals_disabled? &&
string_literals_frozen_by_default?.nil?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/documentation.rb | lib/rubocop/cop/style/documentation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for missing top-level documentation of classes and
# modules. Classes with no body are exempt from the check and so are
# namespace modules - modules that have nothing in their bodies except
# classes, other modules, constant definitions or constant visibility
# declarations.
#
# The documentation requirement is annulled if the class or module has
# a `#:nodoc:` comment next to it. Likewise, `#:nodoc: all` does the
# same for all its children.
#
# @example
# # bad
# class Person
# # ...
# end
#
# module Math
# end
#
# # good
# # Description/Explanation of Person class
# class Person
# # ...
# end
#
# # allowed
# # Class without body
# class Person
# end
#
# # Namespace - A namespace can be a class or a module
# # Containing a class
# module Namespace
# # Description/Explanation of Person class
# class Person
# # ...
# end
# end
#
# # Containing constant visibility declaration
# module Namespace
# class Private
# end
#
# private_constant :Private
# end
#
# # Containing constant definition
# module Namespace
# Public = Class.new
# end
#
# # Macro calls
# module Namespace
# extend Foo
# end
#
# @example AllowedConstants: ['ClassMethods']
#
# # good
# module A
# module ClassMethods
# # ...
# end
# end
#
class Documentation < Base
include DocumentationComment
include RangeHelp
MSG = 'Missing top-level documentation comment for `%<type>s %<identifier>s`.'
# @!method constant_definition?(node)
def_node_matcher :constant_definition?, '{class module casgn}'
# @!method outer_module(node)
def_node_search :outer_module, '(const (const nil? _) _)'
# @!method constant_visibility_declaration?(node)
def_node_matcher :constant_visibility_declaration?, <<~PATTERN
(send nil? {:public_constant :private_constant} ({sym str} _))
PATTERN
# @!method include_statement?(node)
def_node_matcher :include_statement?, <<~PATTERN
(send nil? {:include :extend :prepend} const)
PATTERN
def on_class(node)
return unless node.body
check(node, node.body)
end
def on_module(node)
check(node, node.body)
end
private
def check(node, body)
return if namespace?(body)
return if documentation_comment?(node)
return if constant_allowed?(node)
return if nodoc_self_or_outer_module?(node)
return if include_statement_only?(body)
range = range_between(node.source_range.begin_pos, node.loc.name.end_pos)
message = format(MSG, type: node.type, identifier: identifier(node))
add_offense(range, message: message)
end
def nodoc_self_or_outer_module?(node)
nodoc_comment?(node) ||
(compact_namespace?(node) && nodoc_comment?(outer_module(node).first))
end
def include_statement_only?(body)
return true if include_statement?(body)
body.respond_to?(:children) && body.children.all? { |node| include_statement_only?(node) }
end
def namespace?(node)
return false unless node
if node.begin_type?
node.children.all? { |child| constant_declaration?(child) }
else
constant_definition?(node)
end
end
def constant_declaration?(node)
constant_definition?(node) || constant_visibility_declaration?(node)
end
def constant_allowed?(node)
allowed_constants.include?(node.identifier.short_name)
end
def compact_namespace?(node)
node.loc.name.source.include?('::')
end
# First checks if the :nodoc: comment is associated with the
# class/module. Unless the element is tagged with :nodoc:, the search
# proceeds to check its ancestors for :nodoc: all.
# Note: How end-of-line comments are associated with code changed in
# parser-2.2.0.4.
def nodoc_comment?(node, require_all: false)
return false unless node&.children&.first
nodoc = nodoc(node)
return true if same_line?(nodoc, node) && nodoc?(nodoc, require_all: require_all)
nodoc_comment?(node.parent, require_all: true)
end
def nodoc?(comment, require_all: false)
/^#\s*:nodoc:#{"\s+all\s*$" if require_all}/.match?(comment.text)
end
def nodoc(node)
processed_source.ast_with_comments[node.children.first].first
end
def allowed_constants
@allowed_constants ||= cop_config.fetch('AllowedConstants', []).map(&:intern)
end
def identifier(node)
# Get the fully qualified identifier for a class/module
nodes = [node, *node.each_ancestor(:class, :module)]
identifier = nodes.reverse_each.flat_map { |n| qualify_const(n.identifier) }.join('::')
identifier.sub('::::', '::')
end
def qualify_const(node)
return if node.nil?
if node.type?(:cbase, :self, :call) || node.variable?
node.source
else
[qualify_const(node.namespace), node.short_name].compact
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_percent_q.rb | lib/rubocop/cop/style/redundant_percent_q.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for usage of the %q/%Q syntax when '' or "" would do.
#
# @example
#
# # bad
# name = %q(Bruce Wayne)
# time = %q(8 o'clock)
# question = %q("What did you say?")
#
# # good
# name = 'Bruce Wayne'
# time = "8 o'clock"
# question = '"What did you say?"'
#
class RedundantPercentQ < Base
extend AutoCorrector
MSG = 'Use `%<q_type>s` only for strings that contain both ' \
'single quotes and double quotes%<extra>s.'
DYNAMIC_MSG = ', or for dynamic strings that contain double quotes'
SINGLE_QUOTE = "'"
QUOTE = '"'
EMPTY = ''
PERCENT_Q = '%q'
PERCENT_CAPITAL_Q = '%Q'
STRING_INTERPOLATION_REGEXP = /#\{.+\}/.freeze
ESCAPED_NON_BACKSLASH = /\\[^\\]/.freeze
def on_dstr(node)
return unless string_literal?(node)
check(node)
end
def on_str(node)
# Interpolated strings that contain more than just interpolation
# will call `on_dstr` for the entire string and `on_str` for the
# non interpolated portion of the string
return unless string_literal?(node)
check(node)
end
private
def check(node)
return unless start_with_percent_q_variant?(node)
return if interpolated_quotes?(node) || allowed_percent_q?(node)
add_offense(node) do |corrector|
delimiter = /\A%Q[^"]+\z|'/.match?(node.source) ? QUOTE : SINGLE_QUOTE
corrector.replace(node.loc.begin, delimiter)
corrector.replace(node.loc.end, delimiter)
end
end
def interpolated_quotes?(node)
node.source.include?(SINGLE_QUOTE) && node.source.include?(QUOTE)
end
def allowed_percent_q?(node)
(node.source.start_with?(PERCENT_Q) && acceptable_q?(node)) ||
(node.source.start_with?(PERCENT_CAPITAL_Q) && acceptable_capital_q?(node))
end
def message(node)
src = node.source
extra = if src.start_with?(PERCENT_CAPITAL_Q)
DYNAMIC_MSG
else
EMPTY
end
format(MSG, q_type: src[0, 2], extra: extra)
end
def string_literal?(node)
node.loc?(:begin) && node.loc?(:end)
end
def start_with_percent_q_variant?(string)
string.source.start_with?(PERCENT_Q, PERCENT_CAPITAL_Q)
end
def acceptable_q?(node)
src = node.source
return true if STRING_INTERPOLATION_REGEXP.match?(src)
src.scan(/\\./).any?(ESCAPED_NON_BACKSLASH)
end
def acceptable_capital_q?(node)
src = node.source
src.include?(QUOTE) &&
(STRING_INTERPOLATION_REGEXP.match?(src) ||
(node.str_type? && double_quotes_required?(src)))
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/multiline_method_signature.rb | lib/rubocop/cop/style/multiline_method_signature.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for method signatures that span multiple lines.
#
# @example
#
# # good
#
# def foo(bar, baz)
# end
#
# # bad
#
# def foo(bar,
# baz)
# end
#
class MultilineMethodSignature < Base
include RangeHelp
extend AutoCorrector
MSG = 'Avoid multi-line method signatures.'
def on_def(node)
return unless node.arguments?
return if opening_line(node) == closing_line(node)
return if correction_exceeds_max_line_length?(node)
return unless (begin_of_arguments = node.arguments.loc.begin)
add_offense(node) do |corrector|
autocorrect(corrector, node, begin_of_arguments)
end
end
alias on_defs on_def
private
# rubocop:disable Metrics/AbcSize
def autocorrect(corrector, node, begin_of_arguments)
arguments = node.arguments
joined_arguments = arguments.map(&:source).join(', ')
last_line_source_of_arguments = last_line_source_of_arguments(arguments)
if last_line_source_of_arguments.start_with?(')')
joined_arguments = "#{joined_arguments}#{last_line_source_of_arguments}"
corrector.remove(range_by_whole_lines(arguments.loc.end, include_final_newline: true))
end
arguments_range = range_with_surrounding_space(arguments_range(node), side: :left)
# If the method name isn't on the same line as def, move it directly after def
if arguments_range.first_line != opening_line(node)
corrector.remove(node.loc.name)
corrector.insert_after(node.loc.keyword, " #{node.loc.name.source}")
end
corrector.remove(arguments_range)
corrector.insert_after(begin_of_arguments, joined_arguments)
end
# rubocop:enable Metrics/AbcSize
def last_line_source_of_arguments(arguments)
processed_source[arguments.last_line - 1].strip
end
def opening_line(node)
node.first_line
end
def closing_line(node)
node.arguments.last_line
end
def correction_exceeds_max_line_length?(node)
return false unless max_line_length
indentation_width(node) + definition_width(node) > max_line_length
end
def indentation_width(node)
processed_source.line_indentation(node.source_range.line)
end
def definition_width(node)
node.source_range.begin.join(node.arguments.source_range.end).length
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/static_class.rb | lib/rubocop/cop/style/static_class.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where classes with only class methods can be
# replaced with a module. Classes should be used only when it makes sense to create
# instances out of them.
#
# @safety
# This cop is unsafe, because it is possible that this class is a parent
# for some other subclass, monkey-patched with instance methods or
# a dummy instance is instantiated from it somewhere.
#
# @example
# # bad
# class SomeClass
# def self.some_method
# # body omitted
# end
#
# def self.some_other_method
# # body omitted
# end
# end
#
# # good
# module SomeModule
# module_function
#
# def some_method
# # body omitted
# end
#
# def some_other_method
# # body omitted
# end
# end
#
# # good - has instance method
# class SomeClass
# def instance_method; end
# def self.class_method; end
# end
#
class StaticClass < Base
include RangeHelp
include VisibilityHelp
extend AutoCorrector
MSG = 'Prefer modules to classes with only class methods.'
def on_class(class_node)
return if class_node.parent_class
return unless class_convertible_to_module?(class_node)
add_offense(class_node) do |corrector|
autocorrect(corrector, class_node)
end
end
private
def autocorrect(corrector, class_node)
corrector.replace(class_node.loc.keyword, 'module')
corrector.insert_after(class_node.loc.name, "\nmodule_function\n")
class_elements(class_node).each do |node|
if node.defs_type?
autocorrect_def(corrector, node)
elsif node.sclass_type?
autocorrect_sclass(corrector, node)
end
end
end
def autocorrect_def(corrector, node)
corrector.remove(
range_between(node.receiver.source_range.begin_pos, node.loc.name.begin_pos)
)
end
def autocorrect_sclass(corrector, node)
corrector.remove(
range_between(node.loc.keyword.begin_pos, node.identifier.source_range.end_pos)
)
corrector.remove(node.loc.end)
end
def class_convertible_to_module?(class_node)
nodes = class_elements(class_node)
return false if nodes.empty?
nodes.all? do |node|
(node_visibility(node) == :public && node.defs_type?) ||
sclass_convertible_to_module?(node) ||
node.equals_asgn? ||
extend_call?(node)
end
end
def extend_call?(node)
node.send_type? && node.method?(:extend)
end
def sclass_convertible_to_module?(node)
return false unless node.sclass_type?
class_elements(node).all? do |child|
node_visibility(child) == :public && (child.def_type? || child.equals_asgn?)
end
end
def class_elements(class_node)
class_def = class_node.body
if !class_def
[]
elsif class_def.begin_type?
class_def.children
else
[class_def]
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/format_string.rb | lib/rubocop/cop/style/format_string.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of a single string formatting utility.
# Valid options include `Kernel#format`, `Kernel#sprintf`, and `String#%`.
#
# The detection of `String#%` cannot be implemented in a reliable
# manner for all cases, so only two scenarios are considered -
# if the first argument is a string literal and if the second
# argument is an array literal.
#
# Autocorrection will be applied when using argument is a literal or known built-in conversion
# methods such as `to_d`, `to_f`, `to_h`, `to_i`, `to_r`, `to_s`, and `to_sym` on variables,
# provided that their return value is not an array. For example, when using `to_s`,
# `'%s' % [1, 2, 3].to_s` can be autocorrected without any incompatibility:
#
# [source,ruby]
# ----
# '%s' % [1, 2, 3] #=> '1'
# format('%s', [1, 2, 3]) #=> '[1, 2, 3]'
# '%s' % [1, 2, 3].to_s #=> '[1, 2, 3]'
# ----
#
# @example EnforcedStyle: format (default)
# # bad
# puts sprintf('%10s', 'foo')
# puts '%10s' % 'foo'
#
# # good
# puts format('%10s', 'foo')
#
# @example EnforcedStyle: sprintf
# # bad
# puts format('%10s', 'foo')
# puts '%10s' % 'foo'
#
# # good
# puts sprintf('%10s', 'foo')
#
# @example EnforcedStyle: percent
# # bad
# puts format('%10s', 'foo')
# puts sprintf('%10s', 'foo')
#
# # good
# puts '%10s' % 'foo'
#
class FormatString < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Favor `%<prefer>s` over `%<current>s`.'
RESTRICT_ON_SEND = %i[format sprintf %].freeze
# Known conversion methods whose return value is not an array.
AUTOCORRECTABLE_METHODS = %i[to_d to_f to_h to_i to_r to_s to_sym].freeze
# @!method formatter(node)
def_node_matcher :formatter, <<~PATTERN
{
(send nil? ${:sprintf :format} _ _ ...)
(send {str dstr} $:% ... )
(send !nil? $:% {array hash})
}
PATTERN
# @!method variable_argument?(node)
def_node_matcher :variable_argument?, <<~PATTERN
(send {str dstr} :% #autocorrectable?)
PATTERN
def on_send(node)
formatter(node) do |selector|
detected_style = selector == :% ? :percent : selector
return if detected_style == style
add_offense(node.loc.selector, message: message(detected_style)) do |corrector|
autocorrect(corrector, node)
end
end
end
private
def autocorrectable?(node)
return true if node.lvar_type?
node.send_type? && !AUTOCORRECTABLE_METHODS.include?(node.method_name)
end
def message(detected_style)
format(MSG, prefer: method_name(style), current: method_name(detected_style))
end
def method_name(style_name)
style_name == :percent ? 'String#%' : style_name
end
def autocorrect(corrector, node)
return if variable_argument?(node)
case node.method_name
when :%
autocorrect_from_percent(corrector, node)
when :format, :sprintf
case style
when :percent
autocorrect_to_percent(corrector, node)
when :format, :sprintf
corrector.replace(node.loc.selector, style.to_s)
end
end
end
def autocorrect_from_percent(corrector, node)
percent_rhs = node.first_argument
args = case percent_rhs.type
when :array, :hash
percent_rhs.children.map(&:source).join(', ')
else
percent_rhs.source
end
corrected = "#{style}(#{node.receiver.source}, #{args})"
corrector.replace(node, corrected)
end
def autocorrect_to_percent(corrector, node)
format_arg, *param_args = node.arguments
format = format_arg.source
args = if param_args.one?
format_single_parameter(param_args.last)
else
"[#{param_args.map(&:source).join(', ')}]"
end
corrector.replace(node, "#{format} % #{args}")
end
def format_single_parameter(arg)
source = arg.source
return "{ #{source} }" if arg.hash_type?
arg.send_type? && arg.operator_method? && !arg.parenthesized? ? "(#{source})" : source
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/missing_respond_to_missing.rb | lib/rubocop/cop/style/missing_respond_to_missing.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the presence of `method_missing` without also
# defining `respond_to_missing?`.
#
# Not defining `respond_to_missing?` will cause metaprogramming
# methods like `respond_to?` to behave unexpectedly:
#
# [source,ruby]
# ----
# class StringDelegator
# def initialize(string)
# @string = string
# end
#
# def method_missing(name, *args)
# @string.send(name, *args)
# end
# end
#
# delegator = StringDelegator.new("foo")
# # Claims to not respond to `upcase`.
# delegator.respond_to?(:upcase) # => false
# # But you can call it.
# delegator.upcase # => FOO
# ----
#
# @example
# # bad
# def method_missing(name, *args)
# if @delegate.respond_to?(name)
# @delegate.send(name, *args)
# else
# super
# end
# end
#
# # good
# def respond_to_missing?(name, include_private)
# @delegate.respond_to?(name) || super
# end
#
# def method_missing(name, *args)
# if @delegate.respond_to?(name)
# @delegate.send(name, *args)
# else
# super
# end
# end
#
class MissingRespondToMissing < Base
MSG = 'When using `method_missing`, define `respond_to_missing?`.'
def on_def(node)
return unless node.method?(:method_missing)
return if implements_respond_to_missing?(node)
add_offense(node)
end
alias on_defs on_def
private
def implements_respond_to_missing?(node)
return false unless (grand_parent = node.parent.parent)
grand_parent.each_descendant(node.type) do |descendant|
return true if descendant.method?(:respond_to_missing?)
child = descendant.children.first
return true if child.respond_to?(:method?) && child.method?(:respond_to_missing?)
end
false
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/global_vars.rb | lib/rubocop/cop/style/global_vars.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for uses of global variables.
# It does not report offenses for built-in global variables.
# Built-in global variables are allowed by default. Additionally
# users can allow additional variables via the AllowedVariables option.
#
# Note that backreferences like $1, $2, etc are not global variables.
#
# @example
# # bad
# $foo = 2
# bar = $foo + 5
#
# # good
# FOO = 2
# foo = 2
# $stdin.read
class GlobalVars < Base
MSG = 'Do not introduce global variables.'
# built-in global variables and their English aliases
# https://www.zenspider.com/ruby/quickref.html
BUILT_IN_VARS = %w[
$: $LOAD_PATH
$" $LOADED_FEATURES
$0 $PROGRAM_NAME
$! $ERROR_INFO
$@ $ERROR_POSITION
$; $FS $FIELD_SEPARATOR
$, $OFS $OUTPUT_FIELD_SEPARATOR
$/ $RS $INPUT_RECORD_SEPARATOR
$\\ $ORS $OUTPUT_RECORD_SEPARATOR
$. $NR $INPUT_LINE_NUMBER
$_ $LAST_READ_LINE
$> $DEFAULT_OUTPUT
$< $DEFAULT_INPUT
$$ $PID $PROCESS_ID
$? $CHILD_STATUS
$~ $LAST_MATCH_INFO
$= $IGNORECASE
$* $ARGV
$& $MATCH
$` $PREMATCH
$' $POSTMATCH
$+ $LAST_PAREN_MATCH
$stdin $stdout $stderr
$DEBUG $FILENAME $VERBOSE $SAFE
$-0 $-a $-d $-F $-i $-I $-l $-p $-v $-w
$CLASSPATH $JRUBY_VERSION $JRUBY_REVISION $ENV_JAVA
].map(&:to_sym)
def user_vars
cop_config['AllowedVariables'].map(&:to_sym)
end
def allowed_var?(global_var)
BUILT_IN_VARS.include?(global_var) || user_vars.include?(global_var)
end
def on_gvar(node)
check(node)
end
def on_gvasgn(node)
check(node)
end
def check(node)
add_offense(node.loc.name) unless allowed_var?(node.name)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/collection_methods.rb | lib/rubocop/cop/style/collection_methods.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of consistent method names
# from the Enumerable module.
#
# You can customize the mapping from undesired method to desired method.
#
# e.g. to use `detect` over `find`:
#
# Style/CollectionMethods:
# PreferredMethods:
# find: detect
#
# @safety
# This cop is unsafe because it finds methods by name, without actually
# being able to determine if the receiver is an Enumerable or not, so
# this cop may register false positives.
#
# @example
# # These examples are based on the default mapping for `PreferredMethods`.
#
# # bad
# items.collect
# items.collect!
# items.collect_concat
# items.inject
# items.detect
# items.find_all
# items.member?
#
# # good
# items.map
# items.map!
# items.flat_map
# items.reduce
# items.find
# items.select
# items.include?
#
class CollectionMethods < Base
include MethodPreference
extend AutoCorrector
MSG = 'Prefer `%<prefer>s` over `%<current>s`.'
def on_block(node)
check_method_node(node.send_node)
end
alias on_numblock on_block
alias on_itblock on_block
def on_send(node)
return unless implicit_block?(node)
check_method_node(node)
end
alias on_csend on_send
private
def check_method_node(node)
return unless preferred_methods[node.method_name]
message = message(node)
add_offense(node.loc.selector, message: message) do |corrector|
corrector.replace(node.loc.selector, preferred_method(node.loc.selector.source))
end
end
def implicit_block?(node)
return false unless node.arguments.any?
node.last_argument.block_pass_type? ||
(node.last_argument.sym_type? &&
methods_accepting_symbol.include?(node.method_name.to_s))
end
def message(node)
format(MSG, prefer: preferred_method(node.method_name), current: node.method_name)
end
# Some enumerable methods accept a bare symbol (ie. _not_ Symbol#to_proc) instead
# of a block.
def methods_accepting_symbol
Array(cop_config['MethodsAcceptingSymbol'])
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/or_assignment.rb | lib/rubocop/cop/style/or_assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for potential usage of the `||=` operator.
#
# @example
# # bad
# name = name ? name : 'Bozhidar'
#
# # bad
# name = if name
# name
# else
# 'Bozhidar'
# end
#
# # bad
# unless name
# name = 'Bozhidar'
# end
#
# # bad
# name = 'Bozhidar' unless name
#
# # good - set name to 'Bozhidar', only if it's nil or false
# name ||= 'Bozhidar'
class OrAssignment < Base
extend AutoCorrector
MSG = 'Use the double pipe equals operator `||=` instead.'
# @!method ternary_assignment?(node)
def_node_matcher :ternary_assignment?, <<~PATTERN
({lvasgn ivasgn cvasgn gvasgn} _var
(if
({lvar ivar cvar gvar} _var)
({lvar ivar cvar gvar} _var)
$_))
PATTERN
# @!method unless_assignment?(node)
def_node_matcher :unless_assignment?, <<~PATTERN
(if
({lvar ivar cvar gvar} _var) nil?
({lvasgn ivasgn cvasgn gvasgn} _var
_))
PATTERN
def on_if(node)
return unless unless_assignment?(node)
add_offense(node) { |corrector| autocorrect(corrector, node) }
end
def on_lvasgn(node)
return unless (else_branch = ternary_assignment?(node))
return if else_branch.if_type?
add_offense(node) { |corrector| autocorrect(corrector, node) }
end
alias on_ivasgn on_lvasgn
alias on_cvasgn on_lvasgn
alias on_gvasgn on_lvasgn
private
def autocorrect(corrector, node)
if ternary_assignment?(node)
variable, default = take_variable_and_default_from_ternary(node)
else
variable, default = take_variable_and_default_from_unless(node)
end
corrector.replace(node, "#{variable} ||= #{default.source}")
end
def take_variable_and_default_from_ternary(node)
[node.name, node.expression.else_branch]
end
def take_variable_and_default_from_unless(node)
if node.if_branch
[node.if_branch.name, node.if_branch.expression]
else
[node.else_branch.name, node.else_branch.expression]
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/ascii_comments.rb | lib/rubocop/cop/style/ascii_comments.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for non-ascii (non-English) characters
# in comments. You could set an array of allowed non-ascii chars in
# `AllowedChars` attribute (copyright notice "©" by default).
#
# @example
# # bad
# # Translates from English to 日本語。
#
# # good
# # Translates from English to Japanese
class AsciiComments < Base
include RangeHelp
MSG = 'Use only ascii symbols in comments.'
def on_new_investigation
processed_source.comments.each do |comment|
next if comment.text.ascii_only?
next if only_allowed_non_ascii_chars?(comment.text)
add_offense(first_offense_range(comment))
end
end
private
def first_offense_range(comment)
expression = comment.source_range
first_offense = first_non_ascii_chars(comment.text)
start_position = expression.begin_pos + comment.text.index(first_offense)
end_position = start_position + first_offense.length
range_between(start_position, end_position)
end
def first_non_ascii_chars(string)
string.match(/[^[:ascii:]]+/).to_s
end
def only_allowed_non_ascii_chars?(string)
non_ascii = string.scan(/[^[:ascii:]]/)
(non_ascii - allowed_non_ascii_chars).empty?
end
def allowed_non_ascii_chars
cop_config['AllowedChars'] || []
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_return.rb | lib/rubocop/cop/style/redundant_return.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant `return` expressions.
#
# @example
# # These bad cases should be extended to handle methods whose body is
# # if/else or a case expression with a default branch.
#
# # bad
# def test
# return something
# end
#
# # bad
# def test
# one
# two
# three
# return something
# end
#
# # bad
# def test
# return something if something_else
# end
#
# # good
# def test
# something if something_else
# end
#
# # good
# def test
# if x
# elsif y
# else
# end
# end
#
# @example AllowMultipleReturnValues: false (default)
# # bad
# def test
# return x, y
# end
#
# @example AllowMultipleReturnValues: true
# # good
# def test
# return x, y
# end
#
class RedundantReturn < Base
include RangeHelp
extend AutoCorrector
MSG = 'Redundant `return` detected.'
MULTI_RETURN_MSG = 'To return multiple values, use an array.'
RESTRICT_ON_SEND = %i[define_method define_singleton_method lambda].freeze
def on_send(node)
return unless node.block_literal?
check_branch(node.parent.body)
end
def on_def(node)
check_branch(node.body)
end
alias on_defs on_def
private
def correct_without_arguments(return_node, corrector)
corrector.replace(return_node, 'nil')
end
def correct_with_arguments(return_node, corrector)
if return_node.children.size > 1
add_brackets(corrector, return_node)
elsif hash_without_braces?(return_node.first_argument)
add_braces(corrector, return_node.first_argument)
end
if return_node.splat_argument?
first_argument = return_node.first_argument
corrector.replace(first_argument, first_argument.source.delete_prefix('*'))
end
keyword = range_with_surrounding_space(return_node.loc.keyword, side: :right)
corrector.remove(keyword)
end
def hash_without_braces?(node)
node.hash_type? && !node.braces?
end
def add_brackets(corrector, node)
corrector.insert_before(node.children.first, '[')
corrector.insert_after(node.children.last, ']')
end
def add_braces(corrector, node)
corrector.insert_before(node.children.first, '{')
corrector.insert_after(node.children.last, '}')
end
# rubocop:disable Metrics/CyclomaticComplexity
def check_branch(node)
return unless node
case node.type
when :return then check_return_node(node)
when :case then check_case_node(node)
when :case_match then check_case_match_node(node)
when :if then check_if_node(node)
when :rescue then check_rescue_node(node)
when :resbody then check_resbody_node(node)
when :ensure then check_ensure_node(node)
when :begin, :kwbegin
check_begin_node(node)
end
end
# rubocop:enable Metrics/CyclomaticComplexity
def check_return_node(node)
return if cop_config['AllowMultipleReturnValues'] && node.children.size > 1
add_offense(node.loc.keyword, message: message(node)) do |corrector|
if node.arguments?
correct_with_arguments(node, corrector)
else
correct_without_arguments(node, corrector)
end
end
end
def check_case_node(node)
node.when_branches.each { |when_node| check_branch(when_node.body) }
check_branch(node.else_branch)
end
def check_case_match_node(node)
node.in_pattern_branches.each { |in_pattern_node| check_branch(in_pattern_node.body) }
check_branch(node.else_branch)
end
def check_if_node(node)
return if node.ternary?
check_branch(node.if_branch)
check_branch(node.else_branch)
end
def check_rescue_node(node)
node.branches.each { |branch| check_branch(branch) }
check_branch(node.body) unless node.else?
end
def check_resbody_node(node)
check_branch(node.body)
end
def check_ensure_node(node)
rescue_node = node.node_parts[0]
check_branch(rescue_node)
end
def check_begin_node(node)
last_expr = node.children.last
check_branch(last_expr)
end
def allow_multiple_return_values?
cop_config['AllowMultipleReturnValues'] || false
end
def message(node)
if !allow_multiple_return_values? && node.children.size > 1
"#{MSG} #{MULTI_RETURN_MSG}"
else
MSG
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_self_assignment_branch.rb | lib/rubocop/cop/style/redundant_self_assignment_branch.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where conditional branch makes redundant self-assignment.
#
# It only detects local variable because it may replace state of instance variable,
# class variable, and global variable that have state across methods with `nil`.
#
# @example
#
# # bad
# foo = condition ? bar : foo
#
# # good
# foo = bar if condition
#
# # bad
# foo = condition ? foo : bar
#
# # good
# foo = bar unless condition
#
class RedundantSelfAssignmentBranch < Base
extend AutoCorrector
MSG = 'Remove the self-assignment branch.'
# @!method bad_method?(node)
def_node_matcher :bad_method?, <<~PATTERN
(send nil? :bad_method ...)
PATTERN
def on_lvasgn(node)
expression = node.expression
return unless use_if_and_else_branch?(expression)
if_branch = expression.if_branch
else_branch = expression.else_branch
return if inconvertible_to_modifier?(if_branch, else_branch)
if self_assign?(node.name, if_branch)
register_offense(expression, if_branch, else_branch, 'unless')
elsif self_assign?(node.name, else_branch)
register_offense(expression, else_branch, if_branch, 'if')
end
end
private
def use_if_and_else_branch?(expression)
return false unless expression&.if_type?
!expression.ternary? || !expression.else?
end
def inconvertible_to_modifier?(if_branch, else_branch)
multiple_statements?(if_branch) || multiple_statements?(else_branch) ||
(else_branch.respond_to?(:elsif?) && else_branch.elsif?)
end
def multiple_statements?(branch)
return false unless branch&.begin_type?
!branch.children.empty?
end
def self_assign?(variable, branch)
variable.to_s == branch&.source
end
def register_offense(if_node, offense_branch, opposite_branch, keyword)
add_offense(offense_branch) do |corrector|
assignment_value = opposite_branch ? opposite_branch.source : 'nil'
replacement = "#{assignment_value} #{keyword} #{if_node.condition.source}"
if opposite_branch.respond_to?(:heredoc?) && opposite_branch.heredoc?
replacement += opposite_branch.loc.heredoc_end.with(
begin_pos: opposite_branch.source_range.end_pos
).source
end
corrector.replace(if_node, replacement)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/each_for_simple_loop.rb | lib/rubocop/cop/style/each_for_simple_loop.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for loops which iterate a constant number of times,
# using a `Range` literal and `#each`. This can be done more readably using
# `Integer#times`.
#
# This check only applies if the block takes no parameters.
#
# @example
# # bad
# (1..5).each { }
#
# # good
# 5.times { }
#
# # bad
# (0...10).each {}
#
# # good
# 10.times {}
class EachForSimpleLoop < Base
extend AutoCorrector
MSG = 'Use `Integer#times` for a simple loop which iterates a fixed number of times.'
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return unless offending?(node)
send_node = node.send_node
add_offense(send_node) do |corrector|
range_type, min, max = each_range(node)
max += 1 if range_type == :irange
corrector.replace(send_node, "#{max - min}.times")
end
end
private
def offending?(node)
return false unless node.arguments.empty?
each_range_with_zero_origin?(node) || each_range_without_block_argument?(node)
end
# @!method each_range(node)
def_node_matcher :each_range, <<~PATTERN
(block
(call
(begin
($range (int $_) (int $_)))
:each)
(args ...)
...)
PATTERN
# @!method each_range_with_zero_origin?(node)
def_node_matcher :each_range_with_zero_origin?, <<~PATTERN
(block
(call
(begin
(range (int 0) (int _)))
:each)
(args ...)
...)
PATTERN
# @!method each_range_without_block_argument?(node)
def_node_matcher :each_range_without_block_argument?, <<~PATTERN
(block
(call
(begin
(range (int _) (int _)))
:each)
(args)
...)
PATTERN
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_array_constructor.rb | lib/rubocop/cop/style/redundant_array_constructor.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the instantiation of array using redundant `Array` constructor.
# Autocorrect replaces to array literal which is the simplest and fastest.
#
# @example
#
# # bad
# Array.new([])
# Array[]
# Array([])
# Array.new(['foo', 'foo', 'foo'])
# Array['foo', 'foo', 'foo']
# Array(['foo', 'foo', 'foo'])
#
# # good
# []
# ['foo', 'foo', 'foo']
# Array.new(3, 'foo')
# Array.new(3) { 'foo' }
#
class RedundantArrayConstructor < Base
extend AutoCorrector
MSG = 'Remove the redundant `Array` constructor.'
RESTRICT_ON_SEND = %i[new [] Array].freeze
# @!method redundant_array_constructor(node)
def_node_matcher :redundant_array_constructor, <<~PATTERN
{
(send
(const {nil? cbase} :Array) :new
$(array ...))
(send
(const {nil? cbase} :Array) :[]
$...)
(send
nil? :Array
$(array ...))
}
PATTERN
def on_send(node)
return unless (array_literal = redundant_array_constructor(node))
receiver = node.receiver
selector = node.loc.selector
if node.method?(:new)
range = receiver.source_range.join(selector)
replacement = array_literal
elsif node.method?(:Array)
range = selector
replacement = array_literal
else
range = receiver
replacement = selector.begin.join(node.source_range.end)
end
register_offense(range, node, replacement)
end
private
def register_offense(range, node, replacement)
add_offense(range) do |corrector|
corrector.replace(node, replacement.source)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/if_inside_else.rb | lib/rubocop/cop/style/if_inside_else.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# If the `else` branch of a conditional consists solely of an `if` node,
# it can be combined with the `else` to become an `elsif`.
# This helps to keep the nesting level from getting too deep.
#
# @example
# # bad
# if condition_a
# action_a
# else
# if condition_b
# action_b
# else
# action_c
# end
# end
#
# # good
# if condition_a
# action_a
# elsif condition_b
# action_b
# else
# action_c
# end
#
# @example AllowIfModifier: false (default)
# # bad
# if condition_a
# action_a
# else
# action_b if condition_b
# end
#
# # good
# if condition_a
# action_a
# elsif condition_b
# action_b
# end
#
# @example AllowIfModifier: true
# # good
# if condition_a
# action_a
# else
# action_b if condition_b
# end
#
# # good
# if condition_a
# action_a
# elsif condition_b
# action_b
# end
#
class IfInsideElse < Base
include RangeHelp
extend AutoCorrector
MSG = 'Convert `if` nested inside `else` to `elsif`.'
# rubocop:disable Metrics/CyclomaticComplexity
def on_if(node)
return if node.ternary? || node.unless?
else_branch = node.else_branch
return unless else_branch&.if_type? && else_branch.if?
return if allow_if_modifier_in_else_branch?(else_branch)
add_offense(else_branch.loc.keyword) do |corrector|
next if part_of_ignored_node?(node)
autocorrect(corrector, else_branch)
ignore_node(node)
end
end
# rubocop:enable Metrics/CyclomaticComplexity
private
def autocorrect(corrector, node)
if then?(node)
# If the nested `if` is a then node, correct it first,
# then the next pass will use `correct_to_elsif_from_if_inside_else_form`
IfThenCorrector.new(node, indentation: 0).call(corrector)
return
end
if node.modifier_form?
correct_to_elsif_from_modifier_form(corrector, node)
else
correct_to_elsif_from_if_inside_else_form(corrector, node, node.condition)
end
end
def correct_to_elsif_from_modifier_form(corrector, node)
corrector.replace(node.parent.loc.else, "elsif #{node.condition.source}")
condition_range = range_between(
node.if_branch.source_range.end_pos, node.condition.source_range.end_pos
)
corrector.remove(condition_range)
end
def correct_to_elsif_from_if_inside_else_form(corrector, node, condition) # rubocop:disable Metrics/AbcSize
corrector.replace(node.parent.loc.else, "elsif #{condition.source}")
if_condition_range = if_condition_range(node, condition)
if (if_branch = node.if_branch)
corrector.replace(if_condition_range, range_with_comments(if_branch).source)
corrector.remove(range_with_comments_and_lines(if_branch))
else
corrector.remove(range_by_whole_lines(if_condition_range, include_final_newline: true))
end
corrector.remove(condition)
corrector.remove(range_by_whole_lines(find_end_range(node), include_final_newline: true))
end
def then?(node)
node.loc.begin&.source == 'then'
end
def find_end_range(node)
end_range = node.loc.end
return end_range if end_range
find_end_range(node.parent)
end
def if_condition_range(node, condition)
range_between(node.loc.keyword.begin_pos, condition.source_range.end_pos)
end
def allow_if_modifier_in_else_branch?(else_branch)
allow_if_modifier? && else_branch&.modifier_form?
end
def allow_if_modifier?
cop_config['AllowIfModifier']
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/documentation_method.rb | lib/rubocop/cop/style/documentation_method.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for missing documentation comment for public methods.
# It can optionally be configured to also require documentation for
# non-public methods.
#
# NOTE: This cop allows `initialize` method because `initialize` is
# a special method called from `new`. In some programming languages
# they are called constructor to distinguish it from method.
#
# @example
#
# # bad
#
# class Foo
# def bar
# puts baz
# end
# end
#
# module Foo
# def bar
# puts baz
# end
# end
#
# def foo.bar
# puts baz
# end
#
# # good
#
# class Foo
# # Documentation
# def bar
# puts baz
# end
# end
#
# module Foo
# # Documentation
# def bar
# puts baz
# end
# end
#
# # Documentation
# def foo.bar
# puts baz
# end
#
# @example RequireForNonPublicMethods: false (default)
# # good
# class Foo
# protected
# def do_something
# end
# end
#
# class Foo
# private
# def do_something
# end
# end
#
# @example RequireForNonPublicMethods: true
# # bad
# class Foo
# protected
# def do_something
# end
# end
#
# class Foo
# private
# def do_something
# end
# end
#
# # good
# class Foo
# protected
# # Documentation
# def do_something
# end
# end
#
# class Foo
# private
# # Documentation
# def do_something
# end
# end
#
# @example AllowedMethods: ['method_missing', 'respond_to_missing?']
#
# # good
# class Foo
# def method_missing(name, *args)
# end
#
# def respond_to_missing?(symbol, include_private)
# end
# end
#
class DocumentationMethod < Base
include DocumentationComment
include DefNode
MSG = 'Missing method documentation comment.'
# @!method modifier_node?(node)
def_node_matcher :modifier_node?, <<~PATTERN
(send nil? {:module_function :ruby2_keywords} ...)
PATTERN
def on_def(node)
return if node.method?(:initialize)
parent = node.parent
modifier_node?(parent) ? check(parent) : check(node)
end
alias on_defs on_def
private
def check(node)
return if non_public?(node) && !require_for_non_public_methods?
return if documentation_comment?(node)
return if method_allowed?(node)
add_offense(node)
end
def require_for_non_public_methods?
cop_config['RequireForNonPublicMethods']
end
def method_allowed?(node)
allowed_methods.include?(node.method_name)
end
def allowed_methods
@allowed_methods ||= cop_config.fetch('AllowedMethods', []).map(&:to_sym)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/hash_as_last_array_item.rb | lib/rubocop/cop/style/hash_as_last_array_item.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for presence or absence of braces around hash literal as a last
# array item depending on configuration.
#
# NOTE: This cop will ignore arrays where all items are hashes, regardless of
# EnforcedStyle.
#
# @example EnforcedStyle: braces (default)
# # bad
# [1, 2, one: 1, two: 2]
#
# # good
# [1, 2, { one: 1, two: 2 }]
#
# # good
# [{ one: 1 }, { two: 2 }]
#
# @example EnforcedStyle: no_braces
# # bad
# [1, 2, { one: 1, two: 2 }]
#
# # good
# [1, 2, one: 1, two: 2]
#
# # good
# [{ one: 1 }, { two: 2 }]
class HashAsLastArrayItem < Base
include RangeHelp
include ConfigurableEnforcedStyle
extend AutoCorrector
def on_hash(node)
return if node.children.first&.kwsplat_type?
return unless (array = containing_array(node))
return unless last_array_item?(array, node) && explicit_array?(array)
if braces_style?
check_braces(node)
else
check_no_braces(node)
end
end
private
def containing_array(hash_node)
parent = hash_node.parent
parent if parent&.array_type?
end
def last_array_item?(array, node)
return false if array.child_nodes.all?(&:hash_type?)
array.children.last.equal?(node)
end
def explicit_array?(array)
# an implicit array cannot have an "unbraced" hash
array.square_brackets?
end
def check_braces(node)
return if node.braces?
add_offense(node, message: 'Wrap hash in `{` and `}`.') do |corrector|
corrector.wrap(node, '{', '}')
end
end
def check_no_braces(node)
return unless node.braces?
return if node.children.empty? # Empty hash cannot be "unbraced"
add_offense(node, message: 'Omit the braces around the hash.') do |corrector|
remove_last_element_trailing_comma(corrector, node.parent)
corrector.remove(node.loc.begin)
corrector.remove(node.loc.end)
end
end
def braces_style?
style == :braces
end
def remove_last_element_trailing_comma(corrector, node)
range = range_with_surrounding_space(
node.children.last.source_range,
side: :right
).end.resize(1)
corrector.remove(range) if range.source == ','
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/trailing_comma_in_array_literal.rb | lib/rubocop/cop/style/trailing_comma_in_array_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for trailing comma in array literals.
# The configuration options are:
#
# * `consistent_comma`: Requires a comma after the last item of all non-empty, multiline array
# literals.
# * `comma`: Requires a comma after the last item in an array, but only when each item is on
# its own line.
# * `diff_comma`: Requires a comma after the last item in an array, but only when that item is
# followed by an immediate newline, even if there is an inline comment on the same line.
# * `no_comma`: Does not require a comma after the last item in an array
#
# @example EnforcedStyleForMultiline: consistent_comma
# # bad
# a = [1, 2,]
#
# # good
# a = [1, 2]
#
# # good
# a = [
# 1, 2,
# 3,
# ]
#
# # good
# a = [
# 1, 2, 3,
# ]
#
# # good
# a = [
# 1,
# 2,
# ]
#
# # bad
# a = [1, 2,
# 3, 4]
#
# # good
# a = [1, 2,
# 3, 4,]
#
# @example EnforcedStyleForMultiline: comma
# # bad
# a = [1, 2,]
#
# # good
# a = [1, 2]
#
# # bad
# a = [
# 1, 2,
# 3,
# ]
#
# # good
# a = [
# 1, 2,
# 3
# ]
#
# # bad
# a = [
# 1, 2, 3,
# ]
#
# # good
# a = [
# 1, 2, 3
# ]
#
# # good
# a = [
# 1,
# 2,
# ]
#
# @example EnforcedStyleForMultiline: diff_comma
# # bad
# a = [1, 2,]
#
# # good
# a = [1, 2]
#
# # good
# a = [
# 1, 2,
# 3,
# ]
#
# # good
# a = [
# 1, 2, 3,
# ]
#
# # good
# a = [
# 1,
# 2,
# ]
#
# # bad
# a = [1, 2,
# 3, 4,]
#
# # good
# a = [1, 2,
# 3, 4]
#
# @example EnforcedStyleForMultiline: no_comma (default)
# # bad
# a = [1, 2,]
#
# # good
# a = [
# 1,
# 2
# ]
class TrailingCommaInArrayLiteral < Base
include TrailingComma
extend AutoCorrector
def on_array(node)
return unless node.square_brackets?
check_literal(node, 'item of %<article>s array')
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/string_literals.rb | lib/rubocop/cop/style/string_literals.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks if uses of quotes match the configured preference.
#
# @example EnforcedStyle: single_quotes (default)
# # bad
# "No special symbols"
# "No string interpolation"
# "Just text"
#
# # good
# 'No special symbols'
# 'No string interpolation'
# 'Just text'
# "Wait! What's #{this}!"
#
# @example EnforcedStyle: double_quotes
# # bad
# 'Just some text'
# 'No special chars or interpolation'
#
# # good
# "Just some text"
# "No special chars or interpolation"
# "Every string in #{project} uses double_quotes"
class StringLiterals < Base
include ConfigurableEnforcedStyle
include StringLiteralsHelp
include StringHelp
extend AutoCorrector
MSG_INCONSISTENT = 'Inconsistent quote style.'
def on_dstr(node)
# Strings which are continued across multiple lines using \
# are parsed as a `dstr` node with `str` children
# If one part of that continued string contains interpolations,
# then it will be parsed as a nested `dstr` node
return unless consistent_multiline?
return if node.heredoc?
children = node.children
return unless all_string_literals?(children)
quote_styles = detect_quote_styles(node)
if quote_styles.size > 1
register_offense(node, message: MSG_INCONSISTENT)
else
check_multiline_quote_style(node, quote_styles[0])
end
ignore_node(node)
end
private
def autocorrect(corrector, node)
StringLiteralCorrector.correct(corrector, node, style)
end
def register_offense(node, message: nil)
add_offense(node, message: message || message(node)) do |corrector|
autocorrect(corrector, node)
end
end
def all_string_literals?(nodes)
nodes.all? { |n| n.type?(:str, :dstr) }
end
def detect_quote_styles(node)
styles = node.children.map { |c| c.loc.begin }
# For multi-line strings that only have quote marks
# at the beginning of the first line and the end of
# the last, the begin and end region of each child
# is nil. The quote marks are in the parent node.
return [node.loc.begin.source] if styles.all?(&:nil?)
styles.map(&:source).uniq
end
def message(_node)
if style == :single_quotes
"Prefer single-quoted strings when you don't need string " \
'interpolation or special symbols.'
else
'Prefer double-quoted strings unless you need single quotes to ' \
'avoid extra backslashes for escaping.'
end
end
def offense?(node)
wrong_quotes?(node) && !inside_interpolation?(node)
end
def consistent_multiline?
cop_config['ConsistentQuotesInMultiline']
end
def check_multiline_quote_style(node, quote)
children = node.children
if unexpected_single_quotes?(quote)
all_children_with_quotes = children.all? { |c| wrong_quotes?(c) }
register_offense(node) if all_children_with_quotes
elsif unexpected_double_quotes?(quote) && !accept_child_double_quotes?(children)
register_offense(node)
end
end
def unexpected_single_quotes?(quote)
quote == "'" && style == :double_quotes
end
def unexpected_double_quotes?(quote)
quote == '"' && style == :single_quotes
end
def accept_child_double_quotes?(nodes)
nodes.any? { |n| n.dstr_type? || double_quotes_required?(n.source) }
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/concat_array_literals.rb | lib/rubocop/cop/style/concat_array_literals.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces the use of `Array#push(item)` instead of `Array#concat([item])`
# to avoid redundant array literals.
#
# @safety
# This cop is unsafe, as it can produce false positives if the receiver
# is not an `Array` object.
#
# @example
#
# # bad
# list.concat([foo])
# list.concat([bar, baz])
# list.concat([qux, quux], [corge])
#
# # good
# list.push(foo)
# list.push(bar, baz)
# list.push(qux, quux, corge)
#
class ConcatArrayLiterals < Base
extend AutoCorrector
MSG = 'Use `%<prefer>s` instead of `%<current>s`.'
MSG_FOR_PERCENT_LITERALS =
'Use `push` with elements as arguments without array brackets instead of `%<current>s`.'
RESTRICT_ON_SEND = %i[concat].freeze
# rubocop:disable Metrics
def on_send(node)
return if node.arguments.empty?
return unless node.arguments.all?(&:array_type?)
offense = offense_range(node)
current = offense.source
if (use_percent_literal = node.arguments.any?(&:percent_literal?))
if percent_literals_includes_only_basic_literals?(node)
prefer = preferred_method(node)
message = format(MSG, prefer: prefer, current: current)
else
message = format(MSG_FOR_PERCENT_LITERALS, current: current)
end
else
prefer = preferred_method(node)
message = format(MSG, prefer: prefer, current: current)
end
add_offense(offense, message: message) do |corrector|
if use_percent_literal
corrector.replace(offense, prefer)
else
corrector.replace(node.loc.selector, 'push')
node.arguments.each do |argument|
corrector.remove(argument.loc.begin)
corrector.remove(argument.loc.end)
end
end
end
end
# rubocop:enable Metrics
alias on_csend on_send
private
def offense_range(node)
node.loc.selector.join(node.source_range.end)
end
def preferred_method(node)
new_arguments =
node.arguments.map do |arg|
if arg.percent_literal?
arg.children.map { |child| child.value.inspect }
else
arg.children.map(&:source)
end
end.join(', ')
"push(#{new_arguments})"
end
def percent_literals_includes_only_basic_literals?(node)
node.arguments.select(&:percent_literal?).all? do |arg|
arg.children.all? { |child| child.type?(:str, :sym) }
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/redundant_parentheses.rb | lib/rubocop/cop/style/redundant_parentheses.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant parentheses.
#
# @example
#
# # bad
# (x) if ((y.z).nil?)
#
# # good
# x if y.z.nil?
#
class RedundantParentheses < Base # rubocop:disable Metrics/ClassLength
include Parentheses
extend AutoCorrector
ALLOWED_NODE_TYPES = %i[or send splat kwsplat].freeze
# @!method square_brackets?(node)
def_node_matcher :square_brackets?, <<~PATTERN
(send `{(send _recv _msg) str array hash const #variable?} :[] ...)
PATTERN
# @!method rescue?(node)
def_node_matcher :rescue?, '{^resbody ^^resbody}'
# @!method allowed_pin_operator?(node)
def_node_matcher :allowed_pin_operator?, '^(pin (begin !{lvar ivar cvar gvar}))'
def on_begin(node)
return if !parentheses?(node) || parens_allowed?(node) || ignore_syntax?(node)
check(node)
end
private
def variable?(node)
node.respond_to?(:variable?) && node.variable?
end
def parens_allowed?(node)
empty_parentheses?(node) ||
first_arg_begins_with_hash_literal?(node) ||
rescue?(node) ||
in_pattern_matching_in_method_argument?(node) ||
allowed_pin_operator?(node) ||
allowed_expression?(node)
end
def ignore_syntax?(node)
return false unless (parent = node.parent)
parent.type?(:while_post, :until_post, :match_with_lvasgn) ||
like_method_argument_parentheses?(parent) || multiline_control_flow_statements?(node)
end
def allowed_expression?(node)
allowed_ancestor?(node) ||
allowed_multiple_expression?(node) ||
allowed_ternary?(node) ||
node.parent&.range_type?
end
def allowed_ancestor?(node)
# Don't flag `break(1)`, etc
keyword_ancestor?(node) && parens_required?(node)
end
def allowed_multiple_expression?(node)
return false if node.children.one?
ancestor = node.ancestors.first
return false unless ancestor
!ancestor.type?(:begin, :any_def, :any_block)
end
def allowed_ternary?(node)
return false unless node&.parent&.if_type?
node.parent.ternary? && ternary_parentheses_required?
end
def ternary_parentheses_required?
config = @config.for_cop('Style/TernaryParentheses')
allowed_styles = %w[require_parentheses require_parentheses_when_complex]
config.fetch('Enabled') && allowed_styles.include?(config['EnforcedStyle'])
end
def like_method_argument_parentheses?(node)
return false unless node.type?(:send, :super, :yield)
node.arguments.one? && !node.parenthesized? &&
!node.operator_method? && node.first_argument.begin_type?
end
def multiline_control_flow_statements?(node)
return false unless (parent = node.parent)
return false if parent.single_line?
parent.type?(:return, :next, :break)
end
def empty_parentheses?(node)
# Don't flag `()`
node.children.empty?
end
def first_arg_begins_with_hash_literal?(node)
# Don't flag `method ({key: value})` or `method ({key: value}.method)`
hash_literal = method_chain_begins_with_hash_literal(node.children.first)
if (root_method = node.each_ancestor(:send).to_a.last)
parenthesized = root_method.parenthesized_call?
end
hash_literal && first_argument?(node) && !parentheses?(hash_literal) && !parenthesized
end
def in_pattern_matching_in_method_argument?(begin_node)
return false unless begin_node.parent&.call_type?
return false unless (node = begin_node.children.first)
target_ruby_version <= 2.7 ? node.match_pattern_type? : node.match_pattern_p_type?
end
def method_chain_begins_with_hash_literal(node)
return if node.nil?
return node if node.hash_type?
return unless node.send_type?
method_chain_begins_with_hash_literal(node.children.first)
end
def check(begin_node)
node = begin_node.children.first
if (message = find_offense_message(begin_node, node))
if node.range_type? && !argument_of_parenthesized_method_call?(begin_node, node)
begin_node = begin_node.parent
end
return offense(begin_node, message)
end
check_send(begin_node, node) if call_node?(node)
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
def find_offense_message(begin_node, node)
return 'a keyword' if keyword_with_redundant_parentheses?(node)
return 'a literal' if node.literal? && disallowed_literal?(begin_node, node)
return 'a variable' if node.variable?
return 'a constant' if node.const_type?
if node.assignment? && (begin_node.parent.nil? || begin_node.parent.begin_type?)
return 'an assignment'
end
if node.lambda_or_proc? && (node.braces? || node.send_node.lambda_literal?)
return 'an expression'
end
if disallowed_one_line_pattern_matching?(begin_node, node)
return 'a one-line pattern matching'
end
return 'an interpolated expression' if interpolation?(begin_node)
return 'a method argument' if argument_of_parenthesized_method_call?(begin_node, node)
return 'a one-line rescue' if oneline_rescue_parentheses_required?(begin_node, node)
return if begin_node.chained?
if node.operator_keyword?
return if node.semantic_operator? && begin_node.parent
return if node.multiline? && allow_in_multiline_conditions?
return if ALLOWED_NODE_TYPES.include?(begin_node.parent&.type)
return if !node.and_type? && begin_node.parent&.and_type?
return if begin_node.parent&.if_type? && begin_node.parent.ternary?
'a logical expression'
elsif node.respond_to?(:comparison_method?) && node.comparison_method?
return unless begin_node.parent.nil?
'a comparison expression'
end
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
# @!method interpolation?(node)
def_node_matcher :interpolation?, '[^begin ^^dstr]'
def argument_of_parenthesized_method_call?(begin_node, node)
if node.basic_conditional? || node.rescue_type? || method_call_parentheses_required?(node)
return false
end
return false unless (parent = begin_node.parent)
parent.call_type? && parent.parenthesized? && parent.receiver != begin_node
end
def oneline_rescue_parentheses_required?(begin_node, node)
return false unless node.rescue_type?
return false unless (parent = begin_node.parent)
return false if parent.if_type? && parent.ternary?
return false if parent.conditional? && parent.condition == begin_node
!parent.type?(:call, :array, :pair)
end
def method_call_parentheses_required?(node)
return false unless node.call_type?
(node.receiver.nil? || node.loc.dot) && node.arguments.any?
end
def allow_in_multiline_conditions?
!!config.for_enabled_cop('Style/ParenthesesAroundCondition')['AllowInMultilineConditions']
end
def call_node?(node)
node.call_type? || (node.any_block_type? && node.braces? && !node.lambda_or_proc?)
end
def check_send(begin_node, node)
node = node.send_node if node.any_block_type?
return check_unary(begin_node, node) if node.unary_operation?
return unless method_call_with_redundant_parentheses?(begin_node, node)
return if call_chain_starts_with_int?(begin_node, node) ||
do_end_block_in_method_chain?(begin_node, node)
offense(begin_node, 'a method call')
end
def check_unary(begin_node, node)
return if begin_node.chained?
node = node.children.first while suspect_unary?(node)
return unless method_call_with_redundant_parentheses?(begin_node, node)
offense(begin_node, 'a unary operation')
end
def offense(node, msg)
add_offense(node, message: "Don't use parentheses around #{msg}.") do |corrector|
ParenthesesCorrector.correct(corrector, node)
end
end
def suspect_unary?(node)
node.send_type? && node.unary_operation? && !node.prefix_not?
end
def keyword_ancestor?(node)
node.parent&.keyword?
end
def disallowed_literal?(begin_node, node)
if node.range_type?
return false unless (parent = begin_node.parent)
parent.begin_type? && parent.children.one?
else
!raised_to_power_negative_numeric?(begin_node, node)
end
end
def disallowed_one_line_pattern_matching?(begin_node, node)
if (parent = begin_node.parent)
return false if parent.any_def_type? && parent.endless?
return false if parent.assignment?
end
node.any_match_pattern_type? && node.each_ancestor.none?(&:operator_keyword?)
end
def raised_to_power_negative_numeric?(begin_node, node)
return false unless node.numeric_type?
next_sibling = begin_node.right_sibling
return false unless next_sibling
base_value = node.children.first
base_value.negative? && next_sibling == :**
end
def keyword_with_redundant_parentheses?(node)
return false unless node.keyword?
return true if node.special_keyword?
args = *node
if only_begin_arg?(args)
parentheses?(args.first)
else
args.empty? || parentheses?(node)
end
end
def method_call_with_redundant_parentheses?(begin_node, node)
return false unless node.type?(:call, :super, :yield, :defined?)
return false if node.prefix_not?
return true if singular_parenthesized_parent?(begin_node)
node.arguments.empty? || parentheses?(node) || square_brackets?(node)
end
def singular_parenthesized_parent?(begin_node)
return true unless begin_node.parent
return false if begin_node.parent.type?(:splat, :kwsplat)
parentheses?(begin_node) && begin_node.parent.children.one?
end
def only_begin_arg?(args)
args.one? && args.first&.begin_type?
end
def first_argument?(node)
if first_send_argument?(node) ||
first_super_argument?(node) ||
first_yield_argument?(node)
return true
end
node.each_ancestor.any? { |ancestor| first_argument?(ancestor) }
end
# @!method first_send_argument?(node)
def_node_matcher :first_send_argument?, <<~PATTERN
^(send _ _ equal?(%0) ...)
PATTERN
# @!method first_super_argument?(node)
def_node_matcher :first_super_argument?, <<~PATTERN
^(super equal?(%0) ...)
PATTERN
# @!method first_yield_argument?(node)
def_node_matcher :first_yield_argument?, <<~PATTERN
^(yield equal?(%0) ...)
PATTERN
def call_chain_starts_with_int?(begin_node, send_node)
recv = first_part_of_call_chain(send_node)
recv&.int_type? && (parent = begin_node.parent) &&
parent.send_type? && (parent.method?(:-@) || parent.method?(:+@))
end
def do_end_block_in_method_chain?(begin_node, node)
return false unless (block = node.each_descendant(:any_block).first)
block.keywords? && begin_node.each_ancestor(:call).any?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/nil_comparison.rb | lib/rubocop/cop/style/nil_comparison.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for comparison of something with nil using `==` and
# `nil?`.
#
# Supported styles are: predicate, comparison.
#
# @example EnforcedStyle: predicate (default)
#
# # bad
# if x == nil
# end
#
# # good
# if x.nil?
# end
#
# @example EnforcedStyle: comparison
#
# # bad
# if x.nil?
# end
#
# # good
# if x == nil
# end
#
class NilComparison < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
PREDICATE_MSG = 'Prefer the use of the `nil?` predicate.'
EXPLICIT_MSG = 'Prefer the use of the `==` comparison.'
RESTRICT_ON_SEND = %i[== === nil?].freeze
# @!method nil_comparison?(node)
def_node_matcher :nil_comparison?, '(send _ {:== :===} nil)'
# @!method nil_check?(node)
def_node_matcher :nil_check?, '(send _ :nil?)'
# rubocop:disable Metrics/AbcSize
def on_send(node)
return unless node.receiver
style_check?(node) do
add_offense(node.loc.selector) do |corrector|
if prefer_comparison?
range = node.loc.dot.join(node.loc.selector.end)
corrector.replace(range, ' == nil')
else
range = node.receiver.source_range.end.join(node.source_range.end)
corrector.replace(range, '.nil?')
end
parent = node.parent
corrector.wrap(node, '(', ')') if parent.respond_to?(:method?) && parent.method?(:!)
end
end
end
# rubocop:enable Metrics/AbcSize
private
def message(_node)
prefer_comparison? ? EXPLICIT_MSG : PREDICATE_MSG
end
def style_check?(node, &block)
if prefer_comparison?
nil_check?(node, &block)
else
nil_comparison?(node, &block)
end
end
def prefer_comparison?
style == :comparison
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/array_join.rb | lib/rubocop/cop/style/array_join.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of "*" as a substitute for _join_.
#
# Not all cases can reliably checked, due to Ruby's dynamic
# types, so we consider only cases when the first argument is an
# array literal or the second is a string literal.
#
# @example
#
# # bad
# %w(foo bar baz) * ","
#
# # good
# %w(foo bar baz).join(",")
#
class ArrayJoin < Base
extend AutoCorrector
MSG = 'Favor `Array#join` over `Array#*`.'
RESTRICT_ON_SEND = %i[*].freeze
# @!method join_candidate?(node)
def_node_matcher :join_candidate?, '(send $array :* $str)'
def on_send(node)
return unless (array, join_arg = join_candidate?(node))
add_offense(node.loc.selector) do |corrector|
corrector.replace(node, "#{array.source}.join(#{join_arg.source})")
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/module_member_existence_check.rb | lib/rubocop/cop/style/module_member_existence_check.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for usage of `Module` methods returning arrays that can be replaced
# with equivalent predicates.
#
# Calling a method returning an array then checking if an element is inside
# it is much slower than using an equivalent predicate method. For example,
# `instance_methods.include?` will return an array of all public and protected
# instance methods in the module, then check if a given method is inside that
# array, while `method_defined?` will do direct method lookup, which is much
# faster and consumes less memory.
#
# @example
# # bad
# Array.instance_methods.include?(:size)
# Array.instance_methods.member?(:size)
# Array.instance_methods(true).include?(:size)
#
# Array.instance_methods(false).include?(:find)
#
# # good
# Array.method_defined?(:size)
#
# Array.method_defined?(:find, false)
#
class ModuleMemberExistenceCheck < Base
extend AutoCorrector
MSG = 'Use `%<replacement>s` instead.'
RESTRICT_ON_SEND = %i[instance_methods].freeze
# @!method instance_methods_inclusion?(node)
def_node_matcher :instance_methods_inclusion?, <<~PATTERN
(call
(call _ :instance_methods _?)
{:include? :member?}
_)
PATTERN
def on_send(node) # rubocop:disable Metrics/AbcSize
return unless (parent = node.parent)
return unless instance_methods_inclusion?(parent)
return unless simple_method_argument?(node) && simple_method_argument?(parent)
offense_range = node.location.selector.join(parent.source_range.end)
replacement =
if node.first_argument.nil? || node.first_argument.true_type?
"method_defined?(#{parent.first_argument.source})"
else
"method_defined?(#{parent.first_argument.source}, #{node.first_argument.source})"
end
add_offense(offense_range, message: format(MSG, replacement: replacement)) do |corrector|
corrector.replace(offense_range, replacement)
end
end
alias on_csend on_send
private
def simple_method_argument?(node)
return false if node.splat_argument? || node.block_argument?
return false if node.first_argument&.hash_type?
true
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/format_string_token.rb | lib/rubocop/cop/style/format_string_token.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Use a consistent style for tokens within a format string.
#
# By default, all strings are evaluated. In some cases, this may be undesirable,
# as they could be used as arguments to a method that does not consider
# them to be tokens, but rather other identifiers or just part of the string.
#
# `AllowedMethods` or `AllowedPatterns` can be configured with in order to mark specific
# methods as always allowed, thereby avoiding an offense from the cop. By default, there
# are no allowed methods.
#
# Additionally, the cop can be made conservative by configuring it with
# `Mode: conservative` (default `aggressive`). In this mode, tokens (regardless
# of `EnforcedStyle`) are only considered if used in the format string argument to the
# methods `printf`, `sprintf`, `format` and `%`.
#
# NOTE: Tokens in the `unannotated` style (eg. `%s`) are always treated as if
# configured with `Conservative: true`. This is done in order to prevent false positives,
# because this format is very similar to encoded URLs or Date/Time formatting strings.
#
# @example EnforcedStyle: annotated (default)
#
# # bad
# format('%{greeting}', greeting: 'Hello')
# format('%s', 'Hello')
#
# # good
# format('%<greeting>s', greeting: 'Hello')
#
# @example EnforcedStyle: template
#
# # bad
# format('%<greeting>s', greeting: 'Hello')
# format('%s', 'Hello')
#
# # good
# format('%{greeting}', greeting: 'Hello')
#
# @example EnforcedStyle: unannotated
#
# # bad
# format('%<greeting>s', greeting: 'Hello')
# format('%{greeting}', greeting: 'Hello')
#
# # good
# format('%s', 'Hello')
#
# It is allowed to contain unannotated token
# if the number of them is less than or equals to
# `MaxUnannotatedPlaceholdersAllowed`.
#
# @example MaxUnannotatedPlaceholdersAllowed: 0
#
# # bad
# format('%06d', 10)
# format('%s %s.', 'Hello', 'world')
#
# # good
# format('%<number>06d', number: 10)
#
# @example MaxUnannotatedPlaceholdersAllowed: 1 (default)
#
# # bad
# format('%s %s.', 'Hello', 'world')
#
# # good
# format('%06d', 10)
#
# @example AllowedMethods: [] (default)
#
# # bad
# redirect('foo/%{bar_id}')
#
# @example AllowedMethods: [redirect]
#
# # good
# redirect('foo/%{bar_id}')
#
# @example AllowedPatterns: [] (default)
#
# # bad
# redirect('foo/%{bar_id}')
#
# @example AllowedPatterns: ['redirect']
#
# # good
# redirect('foo/%{bar_id}')
#
# @example Mode: conservative, EnforcedStyle: annotated
# # In `conservative` mode, offenses are only registered for strings
# # given to a known formatting method.
#
# # good
# "%{greeting}"
# foo("%{greeting}")
#
# # bad
# format("%{greeting}", greeting: 'Hello')
# printf("%{greeting}", greeting: 'Hello')
# sprintf("%{greeting}", greeting: 'Hello')
# "%{greeting}" % { greeting: 'Hello' }
#
class FormatStringToken < Base
include ConfigurableEnforcedStyle
include AllowedMethods
include AllowedPattern
extend AutoCorrector
def on_str(node)
return if format_string_token?(node) || use_allowed_method?(node)
detections = collect_detections(node)
return if detections.empty?
return if allowed_unannotated?(detections)
detections.each do |detected_sequence, token_range|
check_sequence(detected_sequence, token_range)
end
end
private
# @!method format_string_in_typical_context?(node)
def_node_matcher :format_string_in_typical_context?, <<~PATTERN
{
^(send _ {:format :sprintf :printf} %0 ...)
^(send %0 :% _)
}
PATTERN
def format_string_token?(node)
!node.value.include?('%') || node.each_ancestor(:xstr, :regexp).any?
end
def use_allowed_method?(node)
send_parent = node.each_ancestor(:send).first
send_parent &&
(allowed_method?(send_parent.method_name) ||
matches_allowed_pattern?(send_parent.method_name))
end
def check_sequence(detected_sequence, token_range)
if detected_sequence.style == style
correct_style_detected
elsif correctable_sequence?(detected_sequence.type)
style_detected(detected_sequence.style)
add_offense(token_range, message: message(detected_sequence.style)) do |corrector|
autocorrect_sequence(corrector, detected_sequence, token_range)
end
end
end
def correctable_sequence?(detected_type)
detected_type == 's' || style == :annotated || style == :unannotated
end
def autocorrect_sequence(corrector, detected_sequence, token_range)
return if style == :unannotated
name = detected_sequence.name
return if name.nil?
flags = detected_sequence.flags
width = detected_sequence.width
precision = detected_sequence.precision
type = detected_sequence.style == :template ? 's' : detected_sequence.type
correction = case style
when :annotated then "%<#{name}>#{flags}#{width}#{precision}#{type}"
when :template then "%#{flags}#{width}#{precision}{#{name}}"
end
corrector.replace(token_range, correction)
end
def allowed_string?(node, detected_style)
(detected_style == :unannotated || conservative?) &&
!format_string_in_typical_context?(node)
end
def message(detected_style)
"Prefer #{message_text(style)} over #{message_text(detected_style)}."
end
# rubocop:disable Style/FormatStringToken
def message_text(style)
{
annotated: 'annotated tokens (like `%<foo>s`)',
template: 'template tokens (like `%{foo}`)',
unannotated: 'unannotated tokens (like `%s`)'
}[style]
end
# rubocop:enable Style/FormatStringToken
def tokens(str_node, &block)
return if str_node.source == '__FILE__'
token_ranges(str_contents(str_node.loc), &block)
end
def str_contents(source_map)
if source_map.is_a?(Parser::Source::Map::Heredoc)
source_map.heredoc_body
elsif source_map.begin
source_map.expression.adjust(begin_pos: +1, end_pos: -1)
else
source_map.expression
end
end
def token_ranges(contents)
format_string = RuboCop::Cop::Utils::FormatString.new(contents.source)
format_string.format_sequences.each do |detected_sequence|
next if detected_sequence.percent?
token = contents.begin.adjust(begin_pos: detected_sequence.begin_pos,
end_pos: detected_sequence.end_pos)
yield(detected_sequence, token)
end
end
def collect_detections(node)
detections = []
tokens(node) do |detected_sequence, token_range|
unless allowed_string?(node, detected_sequence.style)
detections << [detected_sequence, token_range]
end
end
detections
end
def allowed_unannotated?(detections)
return false unless detections.all? do |detected_sequence,|
detected_sequence.style == :unannotated
end
return true if detections.size <= max_unannotated_placeholders_allowed
detections.any? { |detected_sequence,| !correctable_sequence?(detected_sequence.type) }
end
def max_unannotated_placeholders_allowed
cop_config['MaxUnannotatedPlaceholdersAllowed']
end
def conservative?
cop_config.fetch('Mode', :aggressive).to_sym == :conservative
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/keyword_parameters_order.rb | lib/rubocop/cop/style/keyword_parameters_order.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces that optional keyword parameters are placed at the
# end of the parameters list.
#
# This improves readability, because when looking through the source,
# it is expected to find required parameters at the beginning of parameters list
# and optional parameters at the end.
#
# @example
# # bad
# def some_method(first: false, second:, third: 10)
# # body omitted
# end
#
# # good
# def some_method(second:, first: false, third: 10)
# # body omitted
# end
#
# # bad
# do_something do |first: false, second:, third: 10|
# # body omitted
# end
#
# # good
# do_something do |second:, first: false, third: 10|
# # body omitted
# end
#
class KeywordParametersOrder < Base
include RangeHelp
extend AutoCorrector
MSG = 'Place optional keyword parameters at the end of the parameters list.'
def on_kwoptarg(node)
kwarg_nodes = node.right_siblings.select(&:kwarg_type?)
return if kwarg_nodes.empty?
add_offense(node) do |corrector|
defining_node = node.each_ancestor(:any_def, :block).first
next if processed_source.contains_comment?(arguments_range(defining_node))
next unless node.parent.find(&:kwoptarg_type?) == node
autocorrect(corrector, node, defining_node, kwarg_nodes)
end
end
private
def autocorrect(corrector, node, defining_node, kwarg_nodes)
corrector.insert_before(node, "#{kwarg_nodes.map(&:source).join(', ')}, ")
arguments = defining_node.arguments
append_newline_to_last_kwoptarg(arguments, corrector) unless parentheses?(arguments)
remove_kwargs(kwarg_nodes, corrector)
end
def append_newline_to_last_kwoptarg(arguments, corrector)
last_argument = arguments.last
return if last_argument.type?(:kwrestarg, :blockarg)
last_kwoptarg = arguments.reverse.find(&:kwoptarg_type?)
corrector.insert_after(last_kwoptarg, "\n") unless arguments.parent.block_type?
end
def remove_kwargs(kwarg_nodes, corrector)
kwarg_nodes.each do |kwarg|
with_space = range_with_surrounding_space(kwarg.source_range)
corrector.remove(range_with_surrounding_comma(with_space, :left))
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/numeric_literal_prefix.rb | lib/rubocop/cop/style/numeric_literal_prefix.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for octal, hex, binary, and decimal literals using
# uppercase prefixes and corrects them to lowercase prefix
# or no prefix (in case of decimals).
#
# @example EnforcedOctalStyle: zero_with_o (default)
# # bad - missing octal prefix
# num = 01234
#
# # bad - uppercase prefix
# num = 0O1234
# num = 0X12AB
# num = 0B10101
#
# # bad - redundant decimal prefix
# num = 0D1234
# num = 0d1234
#
# # good
# num = 0o1234
# num = 0x12AB
# num = 0b10101
# num = 1234
#
# @example EnforcedOctalStyle: zero_only
# # bad
# num = 0o1234
# num = 0O1234
#
# # good
# num = 01234
class NumericLiteralPrefix < Base
include IntegerNode
extend AutoCorrector
OCTAL_ZERO_ONLY_REGEX = /^0[Oo][0-7]+$/.freeze
OCTAL_REGEX = /^0O?[0-7]+$/.freeze
HEX_REGEX = /^0X[0-9A-F]+$/.freeze
BINARY_REGEX = /^0B[01]+$/.freeze
DECIMAL_REGEX = /^0[dD][0-9]+$/.freeze
OCTAL_ZERO_ONLY_MSG = 'Use 0 for octal literals.'
OCTAL_MSG = 'Use 0o for octal literals.'
HEX_MSG = 'Use 0x for hexadecimal literals.'
BINARY_MSG = 'Use 0b for binary literals.'
DECIMAL_MSG = 'Do not use prefixes for decimal literals.'
def on_int(node)
type = literal_type(node)
return unless type
add_offense(node) do |corrector|
corrector.replace(node, send(:"format_#{type}", node.source))
end
end
private
def message(node)
self.class.const_get(:"#{literal_type(node).upcase}_MSG")
end
def literal_type(node)
literal = integer_part(node)
octal_literal_type(literal) || hex_bin_dec_literal_type(literal)
end
def octal_literal_type(literal)
if OCTAL_ZERO_ONLY_REGEX.match?(literal) && octal_zero_only?
:octal_zero_only
elsif OCTAL_REGEX.match?(literal) && !octal_zero_only?
:octal
end
end
def hex_bin_dec_literal_type(literal)
case literal
when HEX_REGEX
:hex
when BINARY_REGEX
:binary
when DECIMAL_REGEX
:decimal
end
end
def octal_zero_only?
cop_config['EnforcedOctalStyle'] == 'zero_only'
end
def format_octal(source)
source.sub(/^0O?/, '0o')
end
def format_octal_zero_only(source)
source.sub(/^0[Oo]?/, '0')
end
def format_hex(source)
source.sub(/^0X/, '0x')
end
def format_binary(source)
source.sub(/^0B/, '0b')
end
def format_decimal(source)
source.sub(/^0[dD]/, '')
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/open_struct_use.rb | lib/rubocop/cop/style/open_struct_use.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Flags uses of `OpenStruct`, as it is now officially discouraged
# to be used for performance, version compatibility, and potential security issues.
#
# @safety
# Note that this cop may flag false positives; for instance, the following legal
# use of a hand-rolled `OpenStruct` type would be considered an offense:
#
# [source,ruby]
# -----
# module MyNamespace
# class OpenStruct # not the OpenStruct we're looking for
# end
#
# def new_struct
# OpenStruct.new # resolves to MyNamespace::OpenStruct
# end
# end
# -----
#
# @example
#
# # bad
# point = OpenStruct.new(x: 0, y: 1)
#
# # good
# Point = Struct.new(:x, :y)
# point = Point.new(0, 1)
#
# # also good
# point = { x: 0, y: 1 }
#
# # bad
# test_double = OpenStruct.new(a: 'b')
#
# # good (assumes test using rspec-mocks)
# test_double = double
# allow(test_double).to receive(:a).and_return('b')
#
class OpenStructUse < Base
MSG = 'Avoid using `OpenStruct`; use `Struct`, `Hash`, a class or test doubles instead.'
# @!method uses_open_struct?(node)
def_node_matcher :uses_open_struct?, <<~PATTERN
(const {nil? (cbase)} :OpenStruct)
PATTERN
def on_const(node)
return unless uses_open_struct?(node)
return if custom_class_or_module_definition?(node)
add_offense(node)
end
private
def custom_class_or_module_definition?(node)
parent = node.parent
parent.type?(:class, :module) && node.left_siblings.empty?
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/nested_file_dirname.rb | lib/rubocop/cop/style/nested_file_dirname.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for nested `File.dirname`.
# It replaces nested `File.dirname` with the level argument introduced in Ruby 3.1.
#
# @example
#
# # bad
# File.dirname(File.dirname(path))
#
# # good
# File.dirname(path, 2)
#
class NestedFileDirname < Base
include RangeHelp
extend AutoCorrector
extend TargetRubyVersion
MSG = 'Use `dirname(%<path>s, %<level>s)` instead.'
RESTRICT_ON_SEND = %i[dirname].freeze
minimum_target_ruby_version 3.1
# @!method file_dirname?(node)
def_node_matcher :file_dirname?, <<~PATTERN
(send
(const {cbase nil?} :File) :dirname ...)
PATTERN
def on_send(node)
return if file_dirname?(node.parent) || !file_dirname?(node.first_argument)
path, level = path_with_dir_level(node, 1)
return if level < 2
message = format(MSG, path: path, level: level)
range = offense_range(node)
add_offense(range, message: message) do |corrector|
corrector.replace(range, "dirname(#{path}, #{level})")
end
end
private
def path_with_dir_level(node, level)
first_argument = node.first_argument
if file_dirname?(first_argument)
level += 1
path_with_dir_level(first_argument, level)
else
[first_argument.source, level]
end
end
def offense_range(node)
range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/trailing_comma_in_block_args.rb | lib/rubocop/cop/style/trailing_comma_in_block_args.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks whether trailing commas in block arguments are
# required. Blocks with only one argument and a trailing comma require
# that comma to be present. Blocks with more than one argument never
# require a trailing comma.
#
# @safety
# This cop is unsafe because a trailing comma can indicate there are
# more parameters that are not used.
#
# For example:
# [source,ruby]
# ----
# # with a trailing comma
# {foo: 1, bar: 2, baz: 3}.map {|key,| key }
# #=> [:foo, :bar, :baz]
#
# # without a trailing comma
# {foo: 1, bar: 2, baz: 3}.map {|key| key }
# #=> [[:foo, 1], [:bar, 2], [:baz, 3]]
# ----
#
# This can be fixed by replacing the trailing comma with a placeholder
# argument (such as `|key, _value|`).
#
# @example
# # bad
# add { |foo, bar,| foo + bar }
#
# # good
# add { |foo, bar| foo + bar }
#
# # good
# add { |foo,| foo }
#
# # good
# add { foo }
#
# # bad
# add do |foo, bar,|
# foo + bar
# end
#
# # good
# add do |foo, bar|
# foo + bar
# end
#
# # good
# add do |foo,|
# foo
# end
#
# # good
# add do
# foo + bar
# end
class TrailingCommaInBlockArgs < Base
extend AutoCorrector
MSG = 'Useless trailing comma present in block arguments.'
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
# lambda literal (`->`) never has block arguments.
return if node.send_node.lambda_literal?
return unless useless_trailing_comma?(node)
last_comma_pos = last_comma(node).pos
add_offense(last_comma_pos) { |corrector| corrector.replace(last_comma_pos, '') }
end
private
def useless_trailing_comma?(node)
arg_count(node) > 1 && trailing_comma?(node)
end
def arg_count(node)
node.arguments.each_descendant(:arg, :optarg, :kwoptarg).to_a.size
end
def trailing_comma?(node)
argument_tokens(node).last.comma?
end
def last_comma(node)
argument_tokens(node).last
end
def argument_tokens(node)
tokens = processed_source.tokens_within(node)
pipes = tokens.select { |token| token.type == :tPIPE }
begin_pos, end_pos = pipes.map { |pipe| tokens.index(pipe) }
tokens[(begin_pos + 1)..(end_pos - 1)]
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/it_assignment.rb | lib/rubocop/cop/style/it_assignment.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for local variables and method parameters named `it`,
# where `it` can refer to the first anonymous parameter as of Ruby 3.4.
# Use a meaningful variable name instead.
#
# NOTE: Although Ruby allows reassigning `it` in these cases, it could
# cause confusion if `it` is used as a block parameter elsewhere.
#
# @example
# # bad
# it = 5
#
# # good
# var = 5
#
# # bad
# def foo(it)
# end
#
# # good
# def foo(arg)
# end
#
# # bad
# def foo(it = 5)
# end
#
# # good
# def foo(arg = 5)
# end
#
# # bad
# def foo(*it)
# end
#
# # good
# def foo(*args)
# end
#
# # bad
# def foo(it:)
# end
#
# # good
# def foo(arg:)
# end
#
# # bad
# def foo(it: 5)
# end
#
# # good
# def foo(arg: 5)
# end
#
# # bad
# def foo(**it)
# end
#
# # good
# def foo(**kwargs)
# end
#
# # bad
# def foo(&it)
# end
#
# # good
# def foo(&block)
# end
class ItAssignment < Base
MSG = '`it` is the default block parameter; consider another name.'
def on_lvasgn(node)
return unless node.name == :it
add_offense(node.loc.name)
end
alias on_arg on_lvasgn
alias on_optarg on_lvasgn
alias on_restarg on_lvasgn
alias on_blockarg on_lvasgn
alias on_kwarg on_lvasgn
alias on_kwoptarg on_lvasgn
alias on_kwrestarg on_lvasgn
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/strip.rb | lib/rubocop/cop/style/strip.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Identifies places where `lstrip.rstrip` can be replaced by
# `strip`.
#
# @example
# # bad
# 'abc'.lstrip.rstrip
# 'abc'.rstrip.lstrip
#
# # good
# 'abc'.strip
class Strip < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `strip` instead of `%<methods>s`.'
RESTRICT_ON_SEND = %i[lstrip rstrip].freeze
# @!method lstrip_rstrip(node)
def_node_matcher :lstrip_rstrip, <<~PATTERN
{
(call $(call _ :rstrip) :lstrip)
(call $(call _ :lstrip) :rstrip)
}
PATTERN
def on_send(node)
lstrip_rstrip(node) do |first_send|
range = range_between(first_send.loc.selector.begin_pos, node.source_range.end_pos)
message = format(MSG, methods: range.source)
add_offense(range, message: message) do |corrector|
corrector.replace(range, 'strip')
end
end
end
alias on_csend on_send
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/combinable_loops.rb | lib/rubocop/cop/style/combinable_loops.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where multiple consecutive loops over the same data
# can be combined into a single loop. It is very likely that combining them
# will make the code more efficient and more concise.
#
# NOTE: Autocorrection is not applied when the block variable names differ in separate loops,
# as it is impossible to determine which variable name should be prioritized.
#
# @safety
# The cop is unsafe, because the first loop might modify state that the
# second loop depends on; these two aren't combinable.
#
# @example
# # bad
# def method
# items.each do |item|
# do_something(item)
# end
#
# items.each do |item|
# do_something_else(item)
# end
# end
#
# # good
# def method
# items.each do |item|
# do_something(item)
# do_something_else(item)
# end
# end
#
# # bad
# def method
# for item in items do
# do_something(item)
# end
#
# for item in items do
# do_something_else(item)
# end
# end
#
# # good
# def method
# for item in items do
# do_something(item)
# do_something_else(item)
# end
# end
#
# # good
# def method
# each_slice(2) { |slice| do_something(slice) }
# each_slice(3) { |slice| do_something(slice) }
# end
#
class CombinableLoops < Base
extend AutoCorrector
MSG = 'Combine this loop with the previous loop.'
# rubocop:disable Metrics/CyclomaticComplexity
def on_block(node)
return unless node.parent&.begin_type?
return unless collection_looping_method?(node)
return unless same_collection_looping_block?(node, node.left_sibling)
return unless node.body && node.left_sibling.body
add_offense(node) do |corrector|
next unless node.arguments == node.left_sibling.arguments
combine_with_left_sibling(corrector, node)
end
end
# rubocop:enable Metrics/CyclomaticComplexity
alias on_numblock on_block
alias on_itblock on_block
def on_for(node)
return unless node.parent&.begin_type?
return unless same_collection_looping_for?(node, node.left_sibling)
add_offense(node) do |corrector|
combine_with_left_sibling(corrector, node)
end
end
private
def collection_looping_method?(node)
method_name = node.method_name
method_name.start_with?('each') || method_name.end_with?('_each')
end
def same_collection_looping_block?(node, sibling)
return false if sibling.nil? || !sibling.any_block_type?
sibling.method?(node.method_name) &&
sibling.receiver == node.receiver &&
sibling.send_node.arguments == node.send_node.arguments
end
def same_collection_looping_for?(node, sibling)
sibling&.for_type? && node.collection == sibling.collection
end
def combine_with_left_sibling(corrector, node)
corrector.remove(node.left_sibling.body.source_range.end.join(node.left_sibling.loc.end))
corrector.remove(node.source_range.begin.join(node.body.source_range.begin))
correct_end_of_block(corrector, node)
end
def correct_end_of_block(corrector, node)
return unless node.left_sibling.respond_to?(:braces?)
return if node.right_sibling&.any_block_type?
end_of_block = node.left_sibling.braces? ? '}' : ' end'
corrector.remove(node.loc.end)
corrector.insert_before(node.source_range.end, end_of_block)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/safe_navigation_chain_length.rb | lib/rubocop/cop/style/safe_navigation_chain_length.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Enforces safe navigation chains length to not exceed the configured maximum.
# The longer the chain is, the harder it becomes to track what on it could be
# returning `nil`.
#
# There is a potential interplay with `Style/SafeNavigation` - if both are enabled
# and their settings are "incompatible", one of the cops will complain about what
# the other proposes.
#
# E.g. if `Style/SafeNavigation` is configured with `MaxChainLength: 2` (default)
# and this cop is configured with `Max: 1`, then for `foo.bar.baz if foo` the former
# will suggest `foo&.bar&.baz`, which is an offense for the latter.
#
# @example Max: 2 (default)
# # bad
# user&.address&.zip&.upcase
#
# # good
# user&.address&.zip
# user.address.zip if user
#
class SafeNavigationChainLength < Base
MSG = 'Avoid safe navigation chains longer than %<max>d calls.'
def on_csend(node)
safe_navigation_chains = safe_navigation_chains(node)
return if safe_navigation_chains.size < max
add_offense(safe_navigation_chains.last, message: format(MSG, max: max))
end
private
def safe_navigation_chains(node)
node.each_ancestor.with_object([]) do |parent, chains|
break chains unless parent.csend_type?
chains << parent
end
end
def max
cop_config['Max'] || 2
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/encoding.rb | lib/rubocop/cop/style/encoding.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks ensures source files have no utf-8 encoding comments.
# @example
# # bad
# # encoding: UTF-8
# # coding: UTF-8
# # -*- coding: UTF-8 -*-
class Encoding < Base
include RangeHelp
extend AutoCorrector
MSG = 'Unnecessary utf-8 encoding comment.'
ENCODING_PATTERN = /#.*coding\s?[:=]\s?(?:UTF|utf)-8/.freeze
SHEBANG = '#!'
def on_new_investigation
return if processed_source.buffer.source.empty?
comments.each do |line_number, comment|
next unless offense?(comment)
register_offense(line_number, comment)
end
end
private
def comments
processed_source.lines.each.with_index.with_object({}) do |(line, line_number), comments|
next if line.start_with?(SHEBANG)
comment = MagicComment.parse(line)
return comments unless comment.valid?
comments[line_number + 1] = comment
end
end
def offense?(comment)
comment.encoding_specified? && comment.encoding.casecmp('utf-8').zero?
end
def register_offense(line_number, comment)
range = processed_source.buffer.line_range(line_number)
add_offense(range) do |corrector|
text = comment.without(:encoding)
if text.blank?
corrector.remove(range_with_surrounding_space(range, side: :right))
else
corrector.replace(range, text)
end
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/preferred_hash_methods.rb | lib/rubocop/cop/style/preferred_hash_methods.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of methods `Hash#has_key?` and
# `Hash#has_value?`, and suggests using `Hash#key?` and `Hash#value?` instead.
#
# It is configurable to enforce the verbose method names, by using the
# `EnforcedStyle: verbose` configuration.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the receiver
# is a `Hash` or responds to the replacement methods.
#
# @example EnforcedStyle: short (default)
# # bad
# Hash#has_key?
# Hash#has_value?
#
# # good
# Hash#key?
# Hash#value?
#
# @example EnforcedStyle: verbose
# # bad
# Hash#key?
# Hash#value?
#
# # good
# Hash#has_key?
# Hash#has_value?
class PreferredHashMethods < Base
include ConfigurableEnforcedStyle
extend AutoCorrector
MSG = 'Use `Hash#%<prefer>s` instead of `Hash#%<current>s`.'
OFFENDING_SELECTORS = { short: %i[has_key? has_value?], verbose: %i[key? value?] }.freeze
RESTRICT_ON_SEND = OFFENDING_SELECTORS.values.flatten.freeze
def on_send(node)
return unless node.arguments.one? && offending_selector?(node.method_name)
message = message(node.method_name)
add_offense(node.loc.selector, message: message) do |corrector|
corrector.replace(node.loc.selector, proper_method_name(node.loc.selector.source))
end
end
alias on_csend on_send
private
def message(method_name)
format(MSG, prefer: proper_method_name(method_name), current: method_name)
end
def proper_method_name(method_name)
if style == :verbose
"has_#{method_name}"
else
method_name.to_s.delete_prefix('has_')
end
end
def offending_selector?(method_name)
OFFENDING_SELECTORS[style].include?(method_name)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/accessor_grouping.rb | lib/rubocop/cop/style/accessor_grouping.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for grouping of accessors in `class` and `module` bodies.
# By default it enforces accessors to be placed in grouped declarations,
# but it can be configured to enforce separating them in multiple declarations.
#
# NOTE: If there is a method call before the accessor method it is always allowed
# as it might be intended like Sorbet.
#
# NOTE: If there is a RBS::Inline annotation comment just after the accessor method
# it is always allowed.
#
# @example EnforcedStyle: grouped (default)
# # bad
# class Foo
# attr_reader :bar
# attr_reader :bax
# attr_reader :baz
# end
#
# # good
# class Foo
# attr_reader :bar, :bax, :baz
# end
#
# # good
# class Foo
# # may be intended comment for bar.
# attr_reader :bar
#
# sig { returns(String) }
# attr_reader :bax
#
# may_be_intended_annotation :baz
# attr_reader :baz
# end
#
# @example EnforcedStyle: separated
# # bad
# class Foo
# attr_reader :bar, :baz
# end
#
# # good
# class Foo
# attr_reader :bar
# attr_reader :baz
# end
#
class AccessorGrouping < Base
include ConfigurableEnforcedStyle
include RangeHelp
include VisibilityHelp
extend AutoCorrector
GROUPED_MSG = 'Group together all `%<accessor>s` attributes.'
SEPARATED_MSG = 'Use one attribute per `%<accessor>s`.'
def on_class(node)
class_send_elements(node).each do |macro|
next unless macro.attribute_accessor?
check(macro)
end
end
alias on_sclass on_class
alias on_module on_class
private
def check(send_node)
return if previous_line_comment?(send_node) || !groupable_accessor?(send_node)
return unless (grouped_style? && groupable_sibling_accessors(send_node).size > 1) ||
(separated_style? && send_node.arguments.size > 1)
message = message(send_node)
add_offense(send_node, message: message) do |corrector|
autocorrect(corrector, send_node)
end
end
def autocorrect(corrector, node)
if (preferred_accessors = preferred_accessors(node))
corrector.replace(
grouped_style? ? node : range_with_trailing_argument_comment(node),
preferred_accessors
)
else
range = range_with_surrounding_space(node.source_range, side: :left)
corrector.remove(range)
end
end
def previous_line_comment?(node)
comment_line?(processed_source[node.first_line - 2])
end
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def groupable_accessor?(node)
return true unless (previous_expression = node.left_siblings.last)
# Accessors with Sorbet `sig { ... }` blocks shouldn't be groupable.
if previous_expression.block_type?
previous_expression.child_nodes.each do |child_node|
break previous_expression = child_node if child_node.send_type?
end
end
return true unless previous_expression.send_type?
# Accessors with RBS::Inline annotations shouldn't be groupable.
return false if processed_source.comments.any? do |c|
same_line?(c, previous_expression) && c.text.start_with?('#:')
end
previous_expression.attribute_accessor? ||
previous_expression.access_modifier? ||
node.first_line - previous_expression.last_line > 1 # there is a space between nodes
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def class_send_elements(class_node)
class_def = class_node.body
if !class_def || class_def.def_type?
[]
elsif class_def.send_type?
[class_def]
else
class_def.each_child_node(:send).to_a
end
end
def grouped_style?
style == :grouped
end
def separated_style?
style == :separated
end
def groupable_sibling_accessor?(node, sibling)
sibling.attribute_accessor? &&
sibling.method?(node.method_name) &&
node_visibility(sibling) == node_visibility(node) &&
groupable_accessor?(sibling) && !previous_line_comment?(sibling)
end
def groupable_sibling_accessors(send_node)
send_node.parent.each_child_node(:send).select do |sibling|
groupable_sibling_accessor?(send_node, sibling)
end
end
def message(send_node)
msg = grouped_style? ? GROUPED_MSG : SEPARATED_MSG
format(msg, accessor: send_node.method_name)
end
def preferred_accessors(node)
if grouped_style?
return if skip_for_grouping?(node)
accessors = groupable_sibling_accessors(node)
if node.loc == accessors.first.loc || skip_for_grouping?(accessors.first)
group_accessors(node, accessors)
end
else
separate_accessors(node)
end
end
# Group after constants
def skip_for_grouping?(node)
node.right_siblings.any?(&:casgn_type?) &&
node.right_siblings.any? { |n| n.send_type? && groupable_sibling_accessor?(node, n) }
end
def group_accessors(node, accessors)
accessor_names = accessors.flat_map { |accessor| accessor.arguments.map(&:source) }.uniq
"#{node.method_name} #{accessor_names.join(', ')}"
end
def separate_accessors(node)
node.arguments.flat_map do |arg|
lines = [
*processed_source.ast_with_comments[arg].map(&:text),
"#{node.method_name} #{arg.source}"
]
if arg == node.first_argument
lines
else
indent = ' ' * node.loc.column
lines.map { |line| "#{indent}#{line}" }
end
end.join("\n")
end
def range_with_trailing_argument_comment(node)
comment = processed_source.ast_with_comments[node.last_argument].last
if comment
add_range(node.source_range, comment.source_range)
else
node
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/numbered_parameters_limit.rb | lib/rubocop/cop/style/numbered_parameters_limit.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Detects use of an excessive amount of numbered parameters in a
# single block. Having too many numbered parameters can make code too
# cryptic and hard to read.
#
# The cop defaults to registering an offense if there is more than 1 numbered
# parameter but this maximum can be configured by setting `Max`.
#
# @example Max: 1 (default)
# # bad
# use_multiple_numbered_parameters { _1.call(_2, _3, _4) }
#
# # good
# array.each { use_array_element_as_numbered_parameter(_1) }
# hash.each { use_only_hash_value_as_numbered_parameter(_2) }
class NumberedParametersLimit < Base
extend TargetRubyVersion
extend ExcludeLimit
DEFAULT_MAX_VALUE = 1
minimum_target_ruby_version 2.7
exclude_limit 'Max'
MSG = 'Avoid using more than %<max>i numbered %<parameter>s; %<count>i detected.'
NUMBERED_PARAMETER_PATTERN = /\A_[1-9]\z/.freeze
def on_numblock(node)
param_count = numbered_parameter_nodes(node).uniq.count
return if param_count <= max_count
parameter = max_count > 1 ? 'parameters' : 'parameter'
message = format(MSG, max: max_count, parameter: parameter, count: param_count)
add_offense(node, message: message) { self.max = param_count }
end
private
def numbered_parameter_nodes(node)
node.each_descendant(:lvar).select do |lvar_node|
lvar_node.source.match?(NUMBERED_PARAMETER_PATTERN)
end
end
def max_count
max = cop_config.fetch('Max', DEFAULT_MAX_VALUE)
# Ruby does not allow more than 9 numbered parameters
[max, 9].min
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/hash_transform_keys.rb | lib/rubocop/cop/style/hash_transform_keys.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for uses of `+_.each_with_object({}) {...}+`,
# `+_.map {...}.to_h+`, and `+Hash[_.map {...}]+` that are actually just
# transforming the keys of a hash, and tries to use a simpler & faster
# call to `transform_keys` instead.
# It should only be enabled on Ruby version 2.5 or newer.
# (`transform_keys` was added in Ruby 2.5.)
#
# @safety
# This cop is unsafe, as it can produce false positives if we are
# transforming an enumerable of key-value-like pairs that isn't actually
# a hash, e.g.: `[[k1, v1], [k2, v2], ...]`
#
# @example
# # bad
# {a: 1, b: 2}.each_with_object({}) { |(k, v), h| h[foo(k)] = v }
# Hash[{a: 1, b: 2}.collect { |k, v| [foo(k), v] }]
# {a: 1, b: 2}.map { |k, v| [k.to_s, v] }.to_h
# {a: 1, b: 2}.to_h { |k, v| [k.to_s, v] }
#
# # good
# {a: 1, b: 2}.transform_keys { |k| foo(k) }
# {a: 1, b: 2}.transform_keys { |k| k.to_s }
class HashTransformKeys < Base
include HashTransformMethod
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.5
# @!method on_bad_each_with_object(node)
def_node_matcher :on_bad_each_with_object, <<~PATTERN
(block
(call !#array_receiver? :each_with_object (hash))
(args
(mlhs
(arg $_)
(arg _val))
(arg _memo))
(call (lvar _memo) :[]= $!`_memo $(lvar _val)))
PATTERN
# @!method on_bad_hash_brackets_map(node)
def_node_matcher :on_bad_hash_brackets_map, <<~PATTERN
(send
(const _ :Hash)
:[]
(block
(call !#array_receiver? {:map :collect})
(args
(arg $_)
(arg _val))
(array $_ $(lvar _val))))
PATTERN
# @!method on_bad_map_to_h(node)
def_node_matcher :on_bad_map_to_h, <<~PATTERN
(call
(block
(call !#array_receiver? {:map :collect})
(args
(arg $_)
(arg _val))
(array $_ $(lvar _val)))
:to_h)
PATTERN
# @!method on_bad_to_h(node)
def_node_matcher :on_bad_to_h, <<~PATTERN
(block
(call !#array_receiver? :to_h)
(args
(arg $_)
(arg _val))
(array $_ $(lvar _val)))
PATTERN
private
def extract_captures(match)
key_argname, key_body_expr, val_body_expr = *match
Captures.new(key_argname, key_body_expr, val_body_expr)
end
def new_method_name
'transform_keys'
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/character_literal.rb | lib/rubocop/cop/style/character_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of the character literal ?x.
# Starting with Ruby 1.9 character literals are
# essentially one-character strings, so this syntax
# is mostly redundant at this point.
#
# ? character literal can be used to express meta and control character.
# That's a good use case of ? literal so it doesn't count it as an offense.
#
# @example
# # bad
# ?x
#
# # good
# 'x'
#
# # good - control & meta escapes
# ?\C-\M-d
# "\C-\M-d" # same as above
class CharacterLiteral < Base
include StringHelp
extend AutoCorrector
MSG = 'Do not use the character literal - use string literal instead.'
def offense?(node)
# we don't register an offense for things like ?\C-\M-d
node.character_literal? && node.source.size.between?(2, 3)
end
def autocorrect(corrector, node)
string = node.source[1..]
# special character like \n
# or ' which needs to use "" or be escaped.
if string.length == 2 || string == "'"
corrector.replace(node, %("#{string}"))
elsif string.length == 1 # normal character
corrector.replace(node, "'#{string}'")
end
end
# Dummy implementation of method in ConfigurableEnforcedStyle that is
# called from StringHelp.
def opposite_style_detected; end
# Dummy implementation of method in ConfigurableEnforcedStyle that is
# called from StringHelp.
def correct_style_detected; end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/keyword_arguments_merging.rb | lib/rubocop/cop/style/keyword_arguments_merging.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# When passing an existing hash as keyword arguments, provide additional arguments
# directly rather than using `merge`.
#
# Providing arguments directly is more performant than using `merge`, and
# also leads to shorter and simpler code.
#
# @example
# # bad
# some_method(**opts.merge(foo: true))
# some_method(**opts.merge(other_opts))
#
# # good
# some_method(**opts, foo: true)
# some_method(**opts, **other_opts)
#
class KeywordArgumentsMerging < Base
extend AutoCorrector
MSG = 'Provide additional arguments directly rather than using `merge`.'
# @!method merge_kwargs?(node)
def_node_matcher :merge_kwargs?, <<~PATTERN
(send _ _
...
(hash
(kwsplat
$(send $_ :merge $...))
...))
PATTERN
def on_kwsplat(node)
return unless (ancestor = node.parent&.parent)
merge_kwargs?(ancestor) do |merge_node, hash_node, other_hash_node|
add_offense(merge_node) do |corrector|
autocorrect(corrector, node, hash_node, other_hash_node)
end
end
end
private
def autocorrect(corrector, kwsplat_node, hash_node, other_hash_node)
other_hash_node_replacement =
other_hash_node.map do |node|
if node.hash_type?
if node.braces?
node.source[1...-1]
else
node.source
end
else
"**#{node.source}"
end
end.join(', ')
corrector.replace(kwsplat_node, "**#{hash_node.source}, #{other_hash_node_replacement}")
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/single_line_block_params.rb | lib/rubocop/cop/style/single_line_block_params.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks whether the block parameters of a single-line
# method accepting a block match the names specified via configuration.
#
# For instance one can configure `reduce`(`inject`) to use |a, e| as
# parameters.
#
# Configuration option: Methods
# Should be set to use this cop. `Array` of hashes, where each key is the
# method name and value - array of argument names.
#
# @example Methods: [{reduce: %w[a b]}]
# # bad
# foo.reduce { |c, d| c + d }
# foo.reduce { |_, _d| 1 }
#
# # good
# foo.reduce { |a, b| a + b }
# foo.reduce { |a, _b| a }
# foo.reduce { |a, (id, _)| a + id }
# foo.reduce { true }
#
# # good
# foo.reduce do |c, d|
# c + d
# end
class SingleLineBlockParams < Base
extend AutoCorrector
MSG = 'Name `%<method>s` block params `|%<params>s|`.'
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return unless node.single_line?
return unless eligible_method?(node)
return unless eligible_arguments?(node)
method_name = node.method_name
return if args_match?(method_name, node.arguments)
preferred_block_arguments = build_preferred_arguments_map(node, target_args(method_name))
joined_block_arguments = preferred_block_arguments.values.join(', ')
message = format(MSG, method: method_name, params: joined_block_arguments)
add_offense(node.arguments, message: message) do |corrector|
autocorrect(corrector, node, preferred_block_arguments, joined_block_arguments)
end
end
private
def build_preferred_arguments_map(node, preferred_arguments)
preferred_arguments_map = {}
node.arguments.each_with_index do |current_lvar, index|
preferred_argument = preferred_arguments[index]
current_argument = current_lvar.source
preferred_argument = "_#{preferred_argument}" if current_argument.start_with?('_')
preferred_arguments_map[current_argument] = preferred_argument
end
preferred_arguments_map
end
def autocorrect(corrector, node, preferred_block_arguments, joined_block_arguments)
corrector.replace(node.arguments, "|#{joined_block_arguments}|")
node.each_descendant(:lvar) do |lvar|
if (preferred_lvar = preferred_block_arguments[lvar.source])
corrector.replace(lvar, preferred_lvar)
end
end
end
def eligible_arguments?(node)
node.arguments? && node.arguments.to_a.all?(&:arg_type?)
end
def eligible_method?(node)
node.receiver && method_names.include?(node.method_name)
end
def methods
cop_config['Methods']
end
def method_names
methods.map { |method| method_name(method).to_sym }
end
def method_name(method)
method.keys.first
end
def target_args(method_name)
method_name = method_name.to_s
method_hash = methods.find { |m| method_name(m) == method_name }
method_hash[method_name]
end
def args_match?(method_name, args)
actual_args = args.to_a.flat_map(&:to_a)
# Prepending an underscore to mark an unused parameter is allowed, so
# we remove any leading underscores before comparing.
actual_args_no_underscores = actual_args.map { |arg| arg.to_s.sub(/^_+/, '') }
# Allow the arguments if the names match but not all are given
expected_args = target_args(method_name).first(actual_args_no_underscores.size)
actual_args_no_underscores == expected_args
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/block_comments.rb | lib/rubocop/cop/style/block_comments.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Looks for uses of block comments (=begin...=end).
#
# @example
# # bad
# =begin
# Multiple lines
# of comments...
# =end
#
# # good
# # Multiple lines
# # of comments...
#
class BlockComments < Base
include RangeHelp
extend AutoCorrector
MSG = 'Do not use block comments.'
BEGIN_LENGTH = "=begin\n".length
END_LENGTH = "\n=end".length
def on_new_investigation
processed_source.comments.each do |comment|
next unless comment.document?
add_offense(comment) do |corrector|
eq_begin, eq_end, contents = parts(comment)
corrector.remove(eq_begin)
unless contents.empty?
corrector.replace(
contents,
contents.source.gsub(/\A/, '# ').gsub("\n\n", "\n#\n").gsub(/\n(?=[^#])/, "\n# ")
)
end
corrector.remove(eq_end)
end
end
end
private
def parts(comment)
expr = comment.source_range
eq_begin = expr.resize(BEGIN_LENGTH)
eq_end = eq_end_part(comment, expr)
contents = range_between(eq_begin.end_pos, eq_end.begin_pos)
[eq_begin, eq_end, contents]
end
def eq_end_part(comment, expr)
if comment.text.chomp == comment.text
range_between(expr.end_pos - END_LENGTH - 1, expr.end_pos - 2)
else
range_between(expr.end_pos - END_LENGTH, expr.end_pos)
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/hash_slice.rb | lib/rubocop/cop/style/hash_slice.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for usages of `Hash#reject`, `Hash#select`, and `Hash#filter` methods
# that can be replaced with `Hash#slice` method.
#
# This cop should only be enabled on Ruby version 2.5 or higher.
# (`Hash#slice` was added in Ruby 2.5.)
#
# For safe detection, it is limited to commonly used string and symbol comparisons
# when using `==` or `!=`.
#
# This cop doesn't check for `Hash#delete_if` and `Hash#keep_if` because they
# modify the receiver.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the receiver
# is a `Hash` or responds to the replacement method.
#
# @example
#
# # bad
# {foo: 1, bar: 2, baz: 3}.select {|k, v| k == :bar }
# {foo: 1, bar: 2, baz: 3}.reject {|k, v| k != :bar }
# {foo: 1, bar: 2, baz: 3}.filter {|k, v| k == :bar }
# {foo: 1, bar: 2, baz: 3}.select {|k, v| k.eql?(:bar) }
#
# # bad
# {foo: 1, bar: 2, baz: 3}.select {|k, v| %i[bar].include?(k) }
# {foo: 1, bar: 2, baz: 3}.reject {|k, v| !%i[bar].include?(k) }
# {foo: 1, bar: 2, baz: 3}.filter {|k, v| %i[bar].include?(k) }
#
# # good
# {foo: 1, bar: 2, baz: 3}.slice(:bar)
#
# @example AllCops:ActiveSupportExtensionsEnabled: false (default)
#
# # good
# {foo: 1, bar: 2, baz: 3}.select {|k, v| !%i[bar].exclude?(k) }
# {foo: 1, bar: 2, baz: 3}.reject {|k, v| %i[bar].exclude?(k) }
#
# # good
# {foo: 1, bar: 2, baz: 3}.select {|k, v| k.in?(%i[bar]) }
# {foo: 1, bar: 2, baz: 3}.reject {|k, v| !k.in?(%i[bar]) }
#
# @example AllCops:ActiveSupportExtensionsEnabled: true
#
# # bad
# {foo: 1, bar: 2, baz: 3}.select {|k, v| !%i[bar].exclude?(k) }
# {foo: 1, bar: 2, baz: 3}.reject {|k, v| %i[bar].exclude?(k) }
#
# # bad
# {foo: 1, bar: 2, baz: 3}.select {|k, v| k.in?(%i[bar]) }
# {foo: 1, bar: 2, baz: 3}.reject {|k, v| !k.in?(%i[bar]) }
#
# # good
# {foo: 1, bar: 2, baz: 3}.slice(:bar)
#
class HashSlice < Base
include HashSubset
extend TargetRubyVersion
extend AutoCorrector
minimum_target_ruby_version 2.5
private
def semantically_subset_method?(node)
semantically_slice_method?(node)
end
def preferred_method_name
'slice'
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/send.rb | lib/rubocop/cop/style/send.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for the use of the send method.
#
# @example
# # bad
# Foo.send(bar)
# quuz.send(fred)
#
# # good
# Foo.__send__(bar)
# quuz.public_send(fred)
class Send < Base
MSG = 'Prefer `Object#__send__` or `Object#public_send` to `send`.'
RESTRICT_ON_SEND = %i[send].freeze
def on_send(node)
return unless node.arguments?
add_offense(node.loc.selector)
end
alias on_csend on_send
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/empty_string_inside_interpolation.rb | lib/rubocop/cop/style/empty_string_inside_interpolation.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for empty strings being assigned inside string interpolation.
#
# Empty strings are a meaningless outcome inside of string interpolation, so we remove them.
# Alternatively, when configured to do so, we prioritise using empty strings.
#
# While this cop would also apply to variables that are only going to be used as strings,
# RuboCop can't detect that, so we only check inside of string interpolation.
#
# @example EnforcedStyle: trailing_conditional (default)
# # bad
# "#{condition ? 'foo' : ''}"
#
# # good
# "#{'foo' if condition}"
#
# # bad
# "#{condition ? '' : 'foo'}"
#
# # good
# "#{'foo' unless condition}"
#
# @example EnforcedStyle: ternary
# # bad
# "#{'foo' if condition}"
#
# # good
# "#{condition ? 'foo' : ''}"
#
# # bad
# "#{'foo' unless condition}"
#
# # good
# "#{condition ? '' : 'foo'}"
#
class EmptyStringInsideInterpolation < Base
include ConfigurableEnforcedStyle
include Interpolation
extend AutoCorrector
MSG_TRAILING_CONDITIONAL = 'Do not use trailing conditionals in string interpolation.'
MSG_TERNARY = 'Do not return empty strings in string interpolation.'
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Metrics/PerceivedComplexity
def on_interpolation(node)
node.each_child_node(:if) do |child_node|
if style == :trailing_conditional
if empty_if_outcome?(child_node)
ternary_style_autocorrect(child_node, child_node.else_branch.source, 'unless')
end
if empty_else_outcome?(child_node)
ternary_style_autocorrect(child_node, child_node.if_branch.source, 'if')
end
elsif style == :ternary
next unless child_node.modifier_form?
ternary_component = if child_node.unless?
"'' : #{child_node.if_branch.source}"
else
"#{child_node.if_branch.source} : ''"
end
add_offense(node, message: MSG_TRAILING_CONDITIONAL) do |corrector|
corrector.replace(node, "\#{#{child_node.condition.source} ? #{ternary_component}}")
end
end
end
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength, Metrics/PerceivedComplexity
private
def empty_if_outcome?(node)
empty_branch_outcome?(node.if_branch)
end
def empty_else_outcome?(node)
empty_branch_outcome?(node.else_branch)
end
def empty_branch_outcome?(branch)
return false unless branch
branch.nil_type? || (branch.str_type? && branch.value.empty?)
end
def ternary_style_autocorrect(node, outcome, condition)
add_offense(node, message: MSG_TERNARY) do |corrector|
corrector.replace(node, "#{outcome} #{condition} #{node.condition.source}")
end
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/negated_unless.rb | lib/rubocop/cop/style/negated_unless.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for uses of unless with a negated condition. Only unless
# without else are considered. There are three different styles:
#
# * both
# * prefix
# * postfix
#
# @example EnforcedStyle: both (default)
# # enforces `if` for `prefix` and `postfix` conditionals
#
# # bad
# unless !foo
# bar
# end
#
# # good
# if foo
# bar
# end
#
# # bad
# bar unless !foo
#
# # good
# bar if foo
#
# @example EnforcedStyle: prefix
# # enforces `if` for just `prefix` conditionals
#
# # bad
# unless !foo
# bar
# end
#
# # good
# if foo
# bar
# end
#
# # good
# bar unless !foo
#
# @example EnforcedStyle: postfix
# # enforces `if` for just `postfix` conditionals
#
# # bad
# bar unless !foo
#
# # good
# bar if foo
#
# # good
# unless !foo
# bar
# end
class NegatedUnless < Base
include ConfigurableEnforcedStyle
include NegativeConditional
extend AutoCorrector
def on_if(node)
return if node.if? || node.elsif? || node.ternary?
return if correct_style?(node)
message = message(node)
check_negative_conditional(node, message: message) do |corrector|
ConditionCorrector.correct_negative_condition(corrector, node)
end
end
private
def message(node)
format(MSG, inverse: node.inverse_keyword, current: node.keyword)
end
def correct_style?(node)
(style == :prefix && node.modifier_form?) || (style == :postfix && !node.modifier_form?)
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/dir.rb | lib/rubocop/cop/style/dir.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for places where the `#\_\_dir\_\_` method can replace more
# complex constructs to retrieve a canonicalized absolute path to the
# current file.
#
# @example
# # bad
# path = File.expand_path(File.dirname(__FILE__))
#
# # bad
# path = File.dirname(File.realpath(__FILE__))
#
# # good
# path = __dir__
class Dir < Base
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.0
MSG = "Use `__dir__` to get an absolute path to the current file's directory."
RESTRICT_ON_SEND = %i[expand_path dirname].freeze
# @!method dir_replacement?(node)
def_node_matcher :dir_replacement?, <<~PATTERN
{(send (const {nil? cbase} :File) :expand_path (send (const {nil? cbase} :File) :dirname #file_keyword?))
(send (const {nil? cbase} :File) :dirname (send (const {nil? cbase} :File) :realpath #file_keyword?))}
PATTERN
def on_send(node)
dir_replacement?(node) do
add_offense(node) do |corrector|
corrector.replace(node, '__dir__')
end
end
end
private
def file_keyword?(node)
node.str_type? && node.source_range.is?('__FILE__')
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/hash_fetch_chain.rb | lib/rubocop/cop/style/hash_fetch_chain.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Use `Hash#dig` instead of chaining potentially null `fetch` calls.
#
# When `fetch(identifier, nil)` calls are chained on a hash, the expectation
# is that each step in the chain returns either `nil` or another hash,
# and in both cases, these can be simplified with a single call to `dig` with
# multiple arguments.
#
# If the 2nd parameter is `{}` or `Hash.new`, an offense will also be registered,
# as long as the final call in the chain is a nil value. If a non-nil value is given,
# the chain will not be registered as an offense, as the default value cannot be safely
# given with `dig`.
#
# NOTE: See `Style/DigChain` for replacing chains of `dig` calls with
# a single method call.
#
# @safety
# This cop is unsafe because it cannot be guaranteed that the receiver
# is a `Hash` or that `fetch` or `dig` have the expected standard implementation.
#
# @example
# # bad
# hash.fetch('foo', nil)&.fetch('bar', nil)
#
# # bad
# # earlier members of the chain can return `{}` as long as the final `fetch`
# # has `nil` as a default value
# hash.fetch('foo', {}).fetch('bar', nil)
#
# # good
# hash.dig('foo', 'bar')
#
# # ok - not handled by the cop since the final `fetch` value is non-nil
# hash.fetch('foo', {}).fetch('bar', {})
#
class HashFetchChain < Base
extend AutoCorrector
extend TargetRubyVersion
MSG = 'Use `%<replacement>s` instead.'
RESTRICT_ON_SEND = %i[fetch].freeze
minimum_target_ruby_version 2.3
# @!method diggable?(node)
def_node_matcher :diggable?, <<~PATTERN
(call _ :fetch $_arg {nil (hash) (send (const {nil? cbase} :Hash) :new)})
PATTERN
def on_send(node)
return if ignored_node?(node)
return if last_fetch_non_nil?(node)
last_replaceable_node, arguments = inspect_chain(node)
return unless last_replaceable_node
return unless arguments.size > 1
range = last_replaceable_node.selector.join(node.loc.end)
replacement = replacement(arguments)
message = format(MSG, replacement: replacement)
add_offense(range, message: message) do |corrector|
corrector.replace(range, replacement)
end
end
alias on_csend on_send
private
def last_fetch_non_nil?(node)
# When chaining `fetch` methods, `fetch(x, {})` is acceptable within
# the chain, as long as the last method in the chain has a `nil`
# default value.
return false unless node.method?(:fetch)
!node.last_argument&.nil_type?
end
def inspect_chain(node)
arguments = []
while (arg = diggable?(node))
arguments.unshift(arg)
ignore_node(node)
last_replaceable_node = node
node = node.receiver
end
[last_replaceable_node, arguments]
end
def replacement(arguments)
values = arguments.map(&:source).join(', ')
"dig(#{values})"
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/in_pattern_then.rb | lib/rubocop/cop/style/in_pattern_then.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for `in;` uses in `case` expressions.
#
# @example
# # bad
# case expression
# in pattern_a; foo
# in pattern_b; bar
# end
#
# # good
# case expression
# in pattern_a then foo
# in pattern_b then bar
# end
#
class InPatternThen < Base
extend AutoCorrector
extend TargetRubyVersion
minimum_target_ruby_version 2.7
MSG = 'Do not use `in %<pattern>s;`. Use `in %<pattern>s then` instead.'
def on_in_pattern(node)
return if node.multiline? || node.then? || !node.body
pattern = node.pattern
pattern_source = if pattern.match_alt_type?
alternative_pattern_source(pattern)
else
pattern.source
end
add_offense(node.loc.begin, message: format(MSG, pattern: pattern_source)) do |corrector|
corrector.replace(node.loc.begin, ' then')
end
end
private
def alternative_pattern_source(pattern)
collect_alternative_patterns(pattern).join(' | ')
end
def collect_alternative_patterns(pattern)
return pattern.children.map(&:source) unless pattern.children.first.match_alt_type?
pattern_sources = collect_alternative_patterns(pattern.children.first)
pattern_sources << pattern.children[1].source
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/trailing_comma_in_hash_literal.rb | lib/rubocop/cop/style/trailing_comma_in_hash_literal.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for trailing comma in hash literals.
# The configuration options are:
#
# * `consistent_comma`: Requires a comma after the last item of all non-empty, multiline hash
# literals.
# * `comma`: Requires a comma after the last item in a hash, but only when each item is on its
# own line.
# * `diff_comma`: Requires a comma after the last item in a hash, but only when that item is
# followed by an immediate newline, even if there is an inline comment on the same line.
# * `no_comma`: Does not require a comma after the last item in a hash
#
# @example EnforcedStyleForMultiline: consistent_comma
#
# # bad
# a = { foo: 1, bar: 2, }
#
# # good
# a = { foo: 1, bar: 2 }
#
# # good
# a = {
# foo: 1, bar: 2,
# qux: 3,
# }
#
# # good
# a = {
# foo: 1, bar: 2, qux: 3,
# }
#
# # good
# a = {
# foo: 1,
# bar: 2,
# }
#
# # bad
# a = { foo: 1, bar: 2,
# baz: 3, qux: 4 }
#
# # good
# a = { foo: 1, bar: 2,
# baz: 3, qux: 4, }
#
# @example EnforcedStyleForMultiline: comma
#
# # bad
# a = { foo: 1, bar: 2, }
#
# # good
# a = { foo: 1, bar: 2 }
#
# # bad
# a = {
# foo: 1, bar: 2,
# qux: 3,
# }
#
# # good
# a = {
# foo: 1, bar: 2,
# qux: 3
# }
#
# # bad
# a = {
# foo: 1, bar: 2, qux: 3,
# }
#
# # good
# a = {
# foo: 1, bar: 2, qux: 3
# }
#
# # good
# a = {
# foo: 1,
# bar: 2,
# }
#
# @example EnforcedStyleForMultiline: diff_comma
#
# # bad
# a = { foo: 1, bar: 2, }
#
# # good
# a = { foo: 1, bar: 2 }
#
# # good
# a = {
# foo: 1, bar: 2,
# qux: 3,
# }
#
# # good
# a = {
# foo: 1, bar: 2, qux: 3,
# }
#
# # good
# a = {
# foo: 1,
# bar: 2,
# }
#
# # bad
# a = { foo: 1, bar: 2,
# baz: 3, qux: 4, }
#
# # good
# a = { foo: 1, bar: 2,
# baz: 3, qux: 4 }
#
# @example EnforcedStyleForMultiline: no_comma (default)
#
# # bad
# a = { foo: 1, bar: 2, }
#
# # good
# a = {
# foo: 1,
# bar: 2
# }
class TrailingCommaInHashLiteral < Base
include TrailingComma
extend AutoCorrector
def on_hash(node)
check_literal(node, 'item of %<article>s hash')
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
rubocop/rubocop | https://github.com/rubocop/rubocop/blob/99fa0fdd0481910d7d052f4c2ed01ad36178f404/lib/rubocop/cop/style/operator_method_call.rb | lib/rubocop/cop/style/operator_method_call.rb | # frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for redundant dot before operator method call.
# The target operator methods are `|`, `^`, `&`, ``<=>``, `==`, `===`, `=~`, `>`, `>=`, `<`,
# ``<=``, `<<`, `>>`, `+`, `-`, `*`, `/`, `%`, `**`, `~`, `!`, `!=`, and `!~`.
#
# @example
#
# # bad
# foo.+ bar
# foo.& bar
#
# # good
# foo + bar
# foo & bar
#
class OperatorMethodCall < Base
extend AutoCorrector
MSG = 'Redundant dot detected.'
RESTRICT_ON_SEND = %i[| ^ & <=> == === =~ > >= < <= << >> + - * / % ** ~ ! != !~].freeze
INVALID_SYNTAX_ARG_TYPES = %i[
splat kwsplat forwarded_args forwarded_restarg forwarded_kwrestarg block_pass
].freeze
# rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
def on_send(node)
return unless (dot = node.loc.dot)
return if unary_method_no_operator?(node)
return if node.receiver.const_type? || !node.arguments.one?
return unless (rhs = node.first_argument)
return if method_call_with_parenthesized_arg?(rhs)
return if invalid_syntax_argument?(rhs)
add_offense(dot) do |corrector|
wrap_in_parentheses_if_chained(corrector, node)
corrector.replace(dot, ' ')
selector = node.loc.selector
corrector.insert_after(selector, ' ') if insert_space_after?(node)
end
end
# rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
private
# `foo.~@` and `foo.!@` call the method `~` and `!` respectively. While those
# are operator methods, we don't want to actually consider them as such.
def unary_method_no_operator?(node)
return false unless node.nonmutating_unary_operator_method?
node.method_name.to_s != node.selector.source
end
# Checks for an acceptable case of `foo.+(bar).baz`.
def method_call_with_parenthesized_arg?(argument)
return false unless argument.parent.parent&.send_type?
argument.children.first && argument.parent.parenthesized?
end
def invalid_syntax_argument?(argument)
type = argument.hash_type? ? argument.children.first&.type : argument.type
INVALID_SYNTAX_ARG_TYPES.include?(type)
end
def wrap_in_parentheses_if_chained(corrector, node)
return unless node.parent&.call_type?
return if node.parent.first_argument == node
operator = node.loc.selector
ParenthesesCorrector.correct(corrector, node)
corrector.insert_after(operator, ' ')
corrector.wrap(node, '(', ')')
end
def insert_space_after?(node)
rhs = node.first_argument
selector = node.loc.selector
return true if selector.end_pos == rhs.source_range.begin_pos
return false if node.parent&.call_type? # if chained, a space is already added
# For `/` operations, if the RHS starts with a `(` without space,
# add one to avoid a syntax error.
range = selector.end.join(rhs.source_range.begin)
return true if node.method?(:/) && range.source == '('
false
end
end
end
end
end
| ruby | MIT | 99fa0fdd0481910d7d052f4c2ed01ad36178f404 | 2026-01-04T15:37:41.211519Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.