Skip to content
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

Use more specific predicates instead of vague blank? and present? #291

Open
pirj opened this issue Sep 18, 2021 · 2 comments
Open

Use more specific predicates instead of vague blank? and present? #291

pirj opened this issue Sep 18, 2021 · 2 comments

Comments

@pirj
Copy link
Member

pirj commented Sep 18, 2021

If puzzles me what the type of the object is when I read something like:

user = find_user
return if user.blank?

or

results = find_matches
suggest(results) if results.present?

Usually, it's [Array, nil] or [Model, nil], and usage of present?/blank? is superfluous.

Array/Hash/NilClass/TrueClass/FalseClass/String and an arbitrary Object define those methods, disguising the exact object type.
blank? and present? in the Rails Guides

I'd suggest:

  1. using .nil? or an implicit check when it's only important if it's nil or not:
return if user.nil?
# or
return unless user
  1. using any?/empty?/none? when distinguishing between an empty and non-empty Array/Hash

  2. for ActiveRecord::Relation, see Faster Rails: Use exists instead of present? to check if a Record Exists #232 (comment)
    3.1 using any? over present?
    3.2 using empty?/none? over blank?

  3. stop using blank?/present? for booleans

String's blank?/present? are a special case, a string with whitespace only is blank? but not empty?.

cc @marcandre

@pirj
Copy link
Member Author

pirj commented May 3, 2022

@rubocop/style-guide-editors @koic WDYT?

@andyw8
Copy link
Contributor

andyw8 commented May 4, 2022

The only one I really have a strong support for 4. The others can certainly result in clunky code, but I think restricting them may be overly-prescriptive.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants