rails-style-guide
rails-style-guide copied to clipboard
Use more specific predicates instead of vague `blank?` and `present?`
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:
- using
.nil?or an implicit check when it's only important if it'snilor not:
return if user.nil?
# or
return unless user
-
using
any?/empty?/none?when distinguishing between an empty and non-empty Array/Hash -
for
ActiveRecord::Relation, see https://github.com/rubocop/rails-style-guide/issues/232#issuecomment-425848425 3.1 usingany?overpresent?3.2 usingempty?/none?overblank? -
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
@rubocop/style-guide-editors @koic WDYT?
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.