Skip to content

Commit

Permalink
Detect top-level const in ExpandPathArguments
Browse files Browse the repository at this point in the history
Detect `::File.expand_path`, `::Pathname.new` in Style/ExpandPathArguments cop.
  • Loading branch information
biinari authored and bbatsov committed Jul 6, 2020
1 parent bc268f8 commit 91820ea
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/rubocop/cop/style/expand_path_arguments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class ExpandPathArguments < Cop

def_node_matcher :file_expand_path, <<~PATTERN
(send
(const nil? :File) :expand_path
(const {nil? cbase} :File) :expand_path
$_
$_)
PATTERN
Expand All @@ -69,7 +69,7 @@ class ExpandPathArguments < Cop
(send
(send
(send
(const nil? :Pathname) :new
(const {nil? cbase} :Pathname) :new
$_) :parent) :expand_path)
PATTERN

Expand Down
26 changes: 25 additions & 1 deletion spec/rubocop/cop/style/expand_path_arguments_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,18 @@
RUBY
end

it 'registers an offense when using ' \
"`::File.expand_path('./../..', __FILE__)`" do
expect_offense(<<~RUBY)
::File.expand_path('./../..', __FILE__)
^^^^^^^^^^^ Use `expand_path('..', __dir__)` instead of `expand_path('./../..', __FILE__)`.
RUBY

expect_correction(<<~RUBY)
::File.expand_path('..', __dir__)
RUBY
end

it 'registers an offense when using ' \
'`Pathname(__FILE__).parent.expand_path`' do
expect_offense(<<~RUBY)
Expand All @@ -94,14 +106,26 @@
RUBY
end

it 'registers an offense when using ' \
'`::Pathname.new(__FILE__).parent.expand_path`' do
expect_offense(<<~RUBY)
::Pathname.new(__FILE__).parent.expand_path
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `Pathname.new(__dir__).expand_path` instead of `Pathname.new(__FILE__).parent.expand_path`.
RUBY

expect_correction(<<~RUBY)
::Pathname.new(__dir__).expand_path
RUBY
end

it 'does not register an offense when using `File.expand_path(__dir__)`' do
expect_no_offenses(<<~RUBY)
File.expand_path(__dir__)
RUBY
end

it 'does not register an offense when using ' \
'`File.expand_path('..', __dir__)`' do
"`File.expand_path('..', __dir__)`" do
expect_no_offenses(<<~RUBY)
File.expand_path('..', __dir__)
RUBY
Expand Down

0 comments on commit 91820ea

Please sign in to comment.