Showing 1,311 of 1,311 total issues
Remove unnecessary existence check File.exist?
. Open
FileUtils.rm_f(local_file) if File.exist?(local_file)
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks for non-atomic file operation. And then replace it with a nearly equivalent and atomic method.
These can cause problems that are difficult to reproduce, especially in cases of frequent file operations in parallel, such as test runs with parallel_rspec.
For examples: creating a directory if there is none, has the following problems
An exception occurs when the directory didn't exist at the time of exist?
,
but someone else created it before mkdir
was executed.
Subsequent processes are executed without the directory that should be there
when the directory existed at the time of exist?
,
but someone else deleted it shortly afterwards.
Safety:
This cop is unsafe, because autocorrection change to atomic processing. The atomic processing of the replacement destination is not guaranteed to be strictly equivalent to that before the replacement.
Example:
# bad - race condition with another process may result in an error in `mkdir`
unless Dir.exist?(path)
FileUtils.mkdir(path)
end
# good - atomic and idempotent creation
FileUtils.mkdir_p(path)
# bad - race condition with another process may result in an error in `remove`
if File.exist?(path)
FileUtils.remove(path)
end
# good - atomic and idempotent removal
FileUtils.rm_f(path)
Duplicate branch body detected. Open
when ManageIQ::Providers::Kubernetes::ContainerManager::ContainerGroup then true
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks that there are no repeated bodies
within if/unless
, case-when
, case-in
and rescue
constructs.
With IgnoreLiteralBranches: true
, branches are not registered
as offenses if they return a basic literal value (string, symbol,
integer, float, rational, complex, true
, false
, or nil
), or
return an array, hash, regexp or range that only contains one of
the above basic literal values.
With IgnoreConstantBranches: true
, branches are not registered
as offenses if they return a constant value.
Example:
# bad
if foo
do_foo
do_something_else
elsif bar
do_foo
do_something_else
end
# good
if foo || bar
do_foo
do_something_else
end
# bad
case x
when foo
do_foo
when bar
do_foo
else
do_something_else
end
# good
case x
when foo, bar
do_foo
else
do_something_else
end
# bad
begin
do_something
rescue FooError
handle_error
rescue BarError
handle_error
end
# good
begin
do_something
rescue FooError, BarError
handle_error
end
Example: IgnoreLiteralBranches: true
# good
case size
when "small" then 100
when "medium" then 250
when "large" then 1000
else 250
end
Example: IgnoreConstantBranches: true
# good
case size
when "small" then SMALL_SIZE
when "medium" then MEDIUM_SIZE
when "large" then LARGE_SIZE
else MEDIUM_SIZE
end
Use collect { |x| x.manager_uuids.to_a }
instead of collect
method chain. Open
manager_uuids = inventory_collection.parent_inventory_collections.collect(&:manager_uuids).map(&:to_a).flatten
- Create a ticketCreate a ticket
- Exclude checks
Avoid more than 3 levels of block nesting. Open
result[col] = (attrs[:mem_usage_absolute_average] / 100 * total_mem) unless total_mem == 0 || attrs[:mem_usage_absolute_average].nil?
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks for excessive nesting of conditional and looping constructs.
You can configure if blocks are considered using the CountBlocks
option. When set to false
(the default) blocks are not counted
towards the nesting level. Set to true
to count blocks as well.
The maximum level of nesting allowed is configurable.
Do not define constants this way within a block. Open
ALLOCATED_METHODS_WHITELIST = %i[max avg current_value].freeze
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Do not define constants within a block, since the block's scope does not isolate or namespace the constant in any way.
If you are trying to define that constant once, define it outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.
For meta-programming, use const_set
.
Example:
# bad
task :lint do
FILES_TO_LINT = Dir['lib/*.rb']
end
# bad
describe 'making a request' do
class TestRequest; end
end
# bad
module M
extend ActiveSupport::Concern
included do
LIST = []
end
end
# good
task :lint do
files_to_lint = Dir['lib/*.rb']
end
# good
describe 'making a request' do
let(:test_request) { Class.new }
# see also `stub_const` for RSpec
end
# good
module M
extend ActiveSupport::Concern
included do
const_set(:LIST, [])
end
end
Example: AllowedMethods: ['enums'] (default)
# good
# `enums` for Typed Enums via `T::Enum` in Sorbet.
# https://sorbet.org/docs/tenum
class TestEnum < T::Enum
enums do
Foo = new("foo")
end
end
Use filter_map
instead. Open
error ||= credentials.each_value.collect do |val|
if val.kind_of?(Hash)
"credential value must have credential_ref and credential_field" unless val.key?("credential_ref") && val.key?("credential_field")
elsif !val.kind_of?(String)
"credential value must be string or a hash"
- Create a ticketCreate a ticket
- Exclude checks
Wrap expressions with varying precedence with parentheses to avoid ambiguity. Open
t.grouping(Arel::Nodes::Division.new(
Arel::Nodes::NamedFunction.new("CAST", [t[:disk_free_space].as("float")]),
t[:disk_capacity]) * -100 + 100)
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Looks for expressions containing multiple binary operators
where precedence is ambiguous due to lack of parentheses. For example,
in 1 + 2 * 3
, the multiplication will happen before the addition, but
lexically it appears that the addition will happen first.
The cop does not consider unary operators (ie. !a
or -b
) or comparison
operators (ie. a =~ b
) because those are not ambiguous.
NOTE: Ranges are handled by Lint/AmbiguousRange
.
Example:
# bad
a + b * c
a || b && c
a ** b + c
# good (different precedence)
a + (b * c)
a || (b && c)
(a ** b) + c
# good (same precedence)
a + b + c
a * b / c % d
Avoid rescuing the Exception
class. Perhaps you meant to rescue StandardError
? Open
rescue Exception => err
_log.error("SSH connection failed for [#{hostname}] with [#{err.class}: #{err}]")
raise err
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks for rescue
blocks targeting the Exception class.
Example:
# bad
begin
do_something
rescue Exception
handle_exception
end
Example:
# good
begin
do_something
rescue ArgumentError
handle_exception
end
Use s[:enabled] = false; s[:message] = "Provide an IPMI Address"
instead of s.merge!(:enabled => false, :message => "Provide an IPMI Address")
. Open
s.merge!(:enabled => false, :message => "Provide an IPMI Address")
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
This cop identifies places where Hash#merge!
can be replaced by
Hash#[]=
.
Example:
hash.merge!(a: 1)
hash.merge!({'key' => 'value'})
hash.merge!(a: 1, b: 2)
Duplicate branch body detected. Open
else
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks that there are no repeated bodies
within if/unless
, case-when
, case-in
and rescue
constructs.
With IgnoreLiteralBranches: true
, branches are not registered
as offenses if they return a basic literal value (string, symbol,
integer, float, rational, complex, true
, false
, or nil
), or
return an array, hash, regexp or range that only contains one of
the above basic literal values.
With IgnoreConstantBranches: true
, branches are not registered
as offenses if they return a constant value.
Example:
# bad
if foo
do_foo
do_something_else
elsif bar
do_foo
do_something_else
end
# good
if foo || bar
do_foo
do_something_else
end
# bad
case x
when foo
do_foo
when bar
do_foo
else
do_something_else
end
# good
case x
when foo, bar
do_foo
else
do_something_else
end
# bad
begin
do_something
rescue FooError
handle_error
rescue BarError
handle_error
end
# good
begin
do_something
rescue FooError, BarError
handle_error
end
Example: IgnoreLiteralBranches: true
# good
case size
when "small" then 100
when "medium" then 250
when "large" then 1000
else 250
end
Example: IgnoreConstantBranches: true
# good
case size
when "small" then SMALL_SIZE
when "medium" then MEDIUM_SIZE
when "large" then LARGE_SIZE
else MEDIUM_SIZE
end
Avoid immutable Array literals in loops. It is better to extract it into a local variable or a constant. Open
[:on, :off].each do |mode|
- Create a ticketCreate a ticket
- Exclude checks
Use filter_map
instead. Open
rollups.map { |x| rollup_field(x, metric) }.compact.max
- Create a ticketCreate a ticket
- Exclude checks
Use filter_map
instead. Open
connected_components = resource_actions.collect do |ra|
# not find - we need nil when not found
ra.resource_type.constantize.find_by(:id => ra.resource_id)
end.compact
- Create a ticketCreate a ticket
- Exclude checks
Use filter_map
instead. Open
new_ids = hashes.collect { |s| s[:id] }.compact unless hashes.nil?
- Create a ticketCreate a ticket
- Exclude checks
Use filter_map
instead. Open
networks.collect(&:ipaddress).compact.uniq + networks.collect(&:ipv6address).compact.uniq
- Create a ticketCreate a ticket
- Exclude checks
Socket.gethostbyname
is deprecated in favor of Addrinfo#getaddrinfo
. Open
ret = Socket.gethostbyname(ipAddress)
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks for uses of the deprecated class method usages.
Example:
# bad
File.exists?(some_path)
Dir.exists?(some_path)
iterator?
attr :name, true
attr :name, false
ENV.freeze # Calling `Env.freeze` raises `TypeError` since Ruby 2.7.
ENV.clone
ENV.dup # Calling `Env.dup` raises `TypeError` since Ruby 3.1.
Socket.gethostbyname(host)
Socket.gethostbyaddr(host)
# good
File.exist?(some_path)
Dir.exist?(some_path)
block_given?
attr_accessor :name
attr_reader :name
ENV # `ENV.freeze` cannot prohibit changes to environment variables.
ENV.to_h
ENV.to_h # `ENV.dup` cannot dup `ENV`, use `ENV.to_h` to get a copy of `ENV` as a hash.
Addrinfo.getaddrinfo(nodename, service)
Addrinfo.tcp(host, port).getnameinfo
Avoid more than 3 levels of block nesting. Open
if hardware.nil?
EmsRefresh.save_hardware_inventory(self, hw_info)
else
hardware.update(hw_info)
end
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks for excessive nesting of conditional and looping constructs.
You can configure if blocks are considered using the CountBlocks
option. When set to false
(the default) blocks are not counted
towards the nesting level. Set to true
to count blocks as well.
The maximum level of nesting allowed is configurable.
Duplicate branch body detected. Open
when ManageIQ::Providers::Kubernetes::ContainerManager::ContainerNode then true
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks that there are no repeated bodies
within if/unless
, case-when
, case-in
and rescue
constructs.
With IgnoreLiteralBranches: true
, branches are not registered
as offenses if they return a basic literal value (string, symbol,
integer, float, rational, complex, true
, false
, or nil
), or
return an array, hash, regexp or range that only contains one of
the above basic literal values.
With IgnoreConstantBranches: true
, branches are not registered
as offenses if they return a constant value.
Example:
# bad
if foo
do_foo
do_something_else
elsif bar
do_foo
do_something_else
end
# good
if foo || bar
do_foo
do_something_else
end
# bad
case x
when foo
do_foo
when bar
do_foo
else
do_something_else
end
# good
case x
when foo, bar
do_foo
else
do_something_else
end
# bad
begin
do_something
rescue FooError
handle_error
rescue BarError
handle_error
end
# good
begin
do_something
rescue FooError, BarError
handle_error
end
Example: IgnoreLiteralBranches: true
# good
case size
when "small" then 100
when "medium" then 250
when "large" then 1000
else 250
end
Example: IgnoreConstantBranches: true
# good
case size
when "small" then SMALL_SIZE
when "medium" then MEDIUM_SIZE
when "large" then LARGE_SIZE
else MEDIUM_SIZE
end
Avoid rescuing the Exception
class. Perhaps you meant to rescue StandardError
? Open
rescue Exception => err
_log.log_backtrace(err)
task.error(err.message)
task.state_finished
raise
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks for rescue
blocks targeting the Exception class.
Example:
# bad
begin
do_something
rescue Exception
handle_exception
end
Example:
# good
begin
do_something
rescue ArgumentError
handle_exception
end
The use of eval
is a serious security risk. Open
eval("result = \"#{str}\"")
- Read upRead up
- Create a ticketCreate a ticket
- Exclude checks
Checks for the use of Kernel#eval
and Binding#eval
.
Example:
# bad
eval(something)
binding.eval(something)