rubocop / rubocop-rails

A RuboCop extension focused on enforcing Rails best practices and coding conventions.
https://docs.rubocop.org/rubocop-rails
MIT License
813 stars 263 forks source link

`Rails/Presence` enhancement for chained methods #932

Open vlad-pisanov opened 1 year ago

vlad-pisanov commented 1 year ago

I often see the following pattern (especially when controller parameters are processed), which could be written more compactly with .presence:

# bad
foo.present? ? foo.bar : nil
foo.blank? ? nil : foo.bar
foo.bar if foo.present?

# good
foo.presence&.bar
Darhazer commented 1 year ago

I guess the intention in all of those is foo&.bar. I don't see the need of presence, even though the check is for present? / blank? and not merely nil.

vlad-pisanov commented 1 year ago

@Darhazer yeah, one case where this is common is whitespace inputs in web forms:

age = params[:age].present? ? : params[:age].to_i : nil

If params[:age] is " ":

age = params[:age]&.to_i              # 0   ❌
age = params[:age].presence&.to_i     # nil ✔️
koic commented 1 year ago

Yeah, It is better not to omit presence and safe navigation.

nil.to_json           # => "null"
nil.presence.to_json  # => "null"
nil.presence&.to_json # => nil