Rubocop: Lint/SafeNavigationChain shouldn't complain about chaining `to_d`

Created on 8 Jan 2019  路  1Comment  路  Source: rubocop-hq/rubocop

Expected behavior

nil.to_d returns 0.0, so Rubocop should not complain about this case in particular.

Actual behavior

It complains:

# Lint/SafeNavigationChain: Do not chain ordinary method call after safe navigation operator.

Note: Rubocop doesn't complain about the same code with to_f.

Steps to reproduce the problem

Just write the following code and run Rubocop:

amount&.slice.to_d

RuboCop version

0.62.0 (using Parser 2.5.3.0, running on ruby 2.6.0 x86_64-darwin18)
bug

Most helpful comment

This cop is aware of to_f because nil.methods includes :to_f, but to_d is not included.
https://github.com/rubocop-hq/rubocop/blob/b4f89dc1f42a4c5fbe87b9cde22fd75eff2faf00/lib/rubocop/cop/mixin/nil_methods.rb#L10-L12

to_d is defined by bigdecimal/uti library, so it is not defined in the pure environment such as rubocop process.

nil.to_d rescue p $! # => #<NoMethodError: undefined method `to_d' for nil:NilClass>

require 'bigdecimal'
require 'bigdecimal/util'

p nil.to_d # => 0.0

I think this cop should not complain about to_d. Because it is a standard library method.


By the way, if you'd like to use to_d without any offenses soon, you can configure the cop with Whitelist.

Lint/SafeNavigationChain:
  Whitelist:
    - to_d

>All comments

This cop is aware of to_f because nil.methods includes :to_f, but to_d is not included.
https://github.com/rubocop-hq/rubocop/blob/b4f89dc1f42a4c5fbe87b9cde22fd75eff2faf00/lib/rubocop/cop/mixin/nil_methods.rb#L10-L12

to_d is defined by bigdecimal/uti library, so it is not defined in the pure environment such as rubocop process.

nil.to_d rescue p $! # => #<NoMethodError: undefined method `to_d' for nil:NilClass>

require 'bigdecimal'
require 'bigdecimal/util'

p nil.to_d # => 0.0

I think this cop should not complain about to_d. Because it is a standard library method.


By the way, if you'd like to use to_d without any offenses soon, you can configure the cop with Whitelist.

Lint/SafeNavigationChain:
  Whitelist:
    - to_d
Was this page helpful?
0 / 5 - 0 ratings

Related issues

david942j picture david942j  路  3Comments

NobodysNightmare picture NobodysNightmare  路  3Comments

deivid-rodriguez picture deivid-rodriguez  路  3Comments

herwinw picture herwinw  路  3Comments

lepieru picture lepieru  路  3Comments