Skip to content

Cop Idea: ApplicationRecord: delegation of to_s to attributes #1498

@tagliala

Description

@tagliala

⚠️ 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...
end

However, 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:

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions