Skip to content

Rails/Presence enhancement for chained methods #932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
vlad-pisanov opened this issue Feb 8, 2023 · 3 comments · May be fixed by #1461
Open

Rails/Presence enhancement for chained methods #932

vlad-pisanov opened this issue Feb 8, 2023 · 3 comments · May be fixed by #1461
Labels
enhancement New feature or request

Comments

@vlad-pisanov
Copy link
Contributor

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
Copy link
Member

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
Copy link
Contributor Author

@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 koic added the enhancement New feature or request label Apr 4, 2023
@koic
Copy link
Member

koic commented Apr 6, 2023

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

@vlad-pisanov vlad-pisanov linked a pull request Mar 1, 2025 that will close this issue
9 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants