Skip to content

Commit

Permalink
Merge pull request #10824 from koic/make_lint_deprecated_class_method…
Browse files Browse the repository at this point in the history
…s_aware_of_env_clone_and_dup

Make `Lint/DeprecatedClassMethods` aware of `ENV.clone` and `ENV.dup`
  • Loading branch information
koic committed Jul 20, 2022
2 parents 2c4215f + a6bc607 commit 2f8d8c7
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
@@ -0,0 +1 @@
* [#10824](https://github.com/rubocop/rubocop/pull/10824): Make `Lint/DeprecatedClassMethods` aware of `ENV.clone` and `ENV.dup`. ([@koic][])
14 changes: 10 additions & 4 deletions lib/rubocop/cop/lint/deprecated_class_methods.rb
Expand Up @@ -8,22 +8,22 @@ module Lint
# @example
#
# # bad
#
# File.exists?(some_path)
# Dir.exists?(some_path)
# iterator?
# 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)
#
# @example
#
# # good
#
# File.exist?(some_path)
# Dir.exist?(some_path)
# block_given?
# 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
class DeprecatedClassMethods < Base
Expand Down Expand Up @@ -111,6 +111,12 @@ def instance_method?
DeprecatedClassMethod.new(:freeze, class_constant: :ENV) =>
Replacement.new(nil, class_constant: :ENV),

DeprecatedClassMethod.new(:clone, class_constant: :ENV) =>
Replacement.new(:to_h, class_constant: :ENV),

DeprecatedClassMethod.new(:dup, class_constant: :ENV) =>
Replacement.new(:to_h, class_constant: :ENV),

DeprecatedClassMethod.new(:gethostbyaddr, class_constant: :Socket, correctable: false) =>
Replacement.new(:getnameinfo, class_constant: :Addrinfo, instance_method: true),

Expand Down
34 changes: 34 additions & 0 deletions spec/rubocop/cop/lint/deprecated_class_methods_spec.rb
Expand Up @@ -99,6 +99,40 @@
end
end

context 'when using `ENV.clone`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
ENV.clone
^^^^^ `ENV.clone` is deprecated in favor of `ENV.to_h`.
RUBY

expect_correction(<<~RUBY)
ENV.to_h
RUBY
end

it 'does not register an offense for method calls to `ENV` other than `clone`' do
expect_no_offenses('ENV.values')
end
end

context 'when using `ENV.dup`' do
it 'registers an offense' do
expect_offense(<<~RUBY)
ENV.dup
^^^ `ENV.dup` is deprecated in favor of `ENV.to_h`.
RUBY

expect_correction(<<~RUBY)
ENV.to_h
RUBY
end

it 'does not register an offense for method calls to `ENV` other than `dup`' do
expect_no_offenses('ENV.values')
end
end

context 'prefer `Addrinfo#getnameinfo` over `Socket.gethostbyaddr`' do
it 'registers an offense for Socket.gethostbyaddr' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit 2f8d8c7

Please sign in to comment.