-
-
Notifications
You must be signed in to change notification settings - Fork 285
Open
Description
⚠️ Disclaimer: please double check if this proposal makes sense
Is your feature request related to a problem? Please describe.
It is common for ApplicationRecord classes to define their own to_s method, for example, as seen here:
def to_s
name # or title, or email...
endHowever, this can violate the Principle of Least Astonishment (PoLA), as calling to_s on a newly instantiated object may return nil instead of a string.
By using delegate :to_s, to: :name instead, the method will consistently return an empty string when the attribute is nil, ensuring that to_s always returns a string.
Describe the solution you'd like
A cop should suggest the following change:
-def to_s - name -end +delegate :to_s, to: :name
Additional context
This is already the case for properly implemented to_s methods:
- Rails/Delegate Cop will turn
name.to_stodelegate... - Style/RedundantInterpolation will turn
"#{name}"intodelegate...with an intermediatename.to_s
Examples:
# ...
def to_s
name.to_s
end
# ...user.rb:4:3: C: [Correctable] Rails/Delegate: Use delegate to define delegations.
def to_s
^^^
# ...
def to_s
"#{name}"
end
# ...user.rb:5:5: C: [Correctable] Style/RedundantInterpolation: Prefer to_s over string interpolation.
"#{name}"
Metadata
Metadata
Assignees
Labels
No labels