Skip to content

ConvertTry produces invalid Ruby #126

Closed
@celsworth

Description

Expected behavior

Given this source:

class Foo
  def foo
    self.try(:bar).try(:baz)
  end
end

And this Rubocop config:

AllCops:
  TargetRubyVersion: 2.3

Rails:
  Enabled: true

Rails/SafeNavigation:
  ConvertTry: true

I expected auto-correction to produce working Ruby.

Actual behavior

Auto-correction produces this output:

# frozen_string_literal: true

class Foo
  def foo
    &.bar&.baz
  end
end

Which does not parse. The Rubocop output is:

Inspecting 1 file
E

Offenses:

test.rb:1:1: C: [Corrected] Style/FrozenStringLiteralComment: Missing magic comment # frozen_string_literal: true.
class Foo
^
test.rb:3:1: E: Lint/Syntax: class definition in method body
(Using Ruby 2.3 parser; configure using TargetRubyVersion parameter, under AllCops)
class Foo
^^^^^
test.rb:3:5: C: [Corrected] Rails/SafeNavigation: Use safe navigation (&.) instead of try.
    self.try(:bar).try(:baz)
    ^^^^^^^^^^^^^^^^^^^^^^^^
test.rb:3:5: C: [Corrected] Style/RedundantSelf: Redundant self detected.
    self.try(:bar).try(:baz)
    ^^^^^^^^^^^^^^
test.rb:5:10: E: Lint/Syntax: unexpected token tANDDOT
(Using Ruby 2.3 parser; configure using TargetRubyVersion parameter, under AllCops)
    &.bar&.baz
         ^^

1 file inspected, 5 offenses detected, 3 offenses corrected

Steps to reproduce the problem

Run rubocop -a with the above source and config. Note that setting the target Ruby version to 2.2 (the lowest supported) produces working Ruby (it leaves the try in place).

RuboCop version

0.68.0 (using Parser 2.6.0.0, running on ruby 2.3.3 x86_64-darwin17)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions