Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style/FormatString cop breaks code #7130

Closed
michiomochi opened this issue Jun 12, 2019 · 4 comments
Closed

Style/FormatString cop breaks code #7130

michiomochi opened this issue Jun 12, 2019 · 4 comments
Labels

Comments

@michiomochi
Copy link

michiomochi commented Jun 12, 2019

Rubocop auto-corrector breaks code by Style/FormatString cop.

Before code is

def hoge
  "%08x-%04x-%04x-%04x-%04x%08x" % ary
end

Execute auto-correct

> bundle exec rubocop -a

After code is

def hoge
  format("%08x-%04x-%04x-%04x-%04x%08x", ary)
end

Expected behavior

No effort.

Actual behavior

Fix to unexpected code.

RuboCop version

> bundle exec rubocop -v
0.71.0
@koic koic added the bug label Jun 12, 2019
@pocke
Copy link
Collaborator

pocke commented Jun 12, 2019

String#% can receive an array, but format cannot receive it.

"%02x" % 1 # => "01"
"%02x" % [1] # => "01"
"%02x-%02x" % [1, 2] # => "01-02"

format("%02x", 1)# => "01"
format("%02x", [1])# => TypeError
format("%02x-%02x", [1, 2]) # => TypeError
format("%02x-%02x", 1, 2) # => "01-02"

I think we should mark the auto-correction as unsafe.

@tejasbubane
Copy link
Contributor

@pocke Is is a good idea to not register offense when second argument to String#% is a variable?

@pocke
Copy link
Collaborator

pocke commented Jun 12, 2019

@pocke Is is a good idea to not register offense when second argument to String#% is a variable?

It makes sense, but I prefer changing auto-correct safety.
Because if the cop does not register offense, user has no way to know format method.


By the way, I got other ideas.

First, ignore only auto-correction when the argument is a variable.
The cop registers an offesne for String% with a variable but does not apply auto-correction.

Second, I guess we can use splat operator for a variable, like format("str", *variable).
I think it is a better way, but I'm not sure splat operator does not change meaning anytime.

@tejasbubane
Copy link
Contributor

I guess we can use splat operator for a variable, like format("str", *variable)

This will be an issue if variable is a hash. First approach looks better.

tejasbubane added a commit to tejasbubane/rubocop that referenced this issue Jun 25, 2019
… argument is variable

For `String#%` is second argument is variable, flag offense but skip
autocorrect. It is not possible for rubocop to know if variable is
array in which case the autocorrect leads to invalid code.

Closes rubocop#7130.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
4 participants