Skip to content

Instantly share code, notes, and snippets.

@allard
Created May 2, 2023 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allard/9a37a8dfc5bc5beca64e7db7e3468795 to your computer and use it in GitHub Desktop.
Save allard/9a37a8dfc5bc5beca64e7db7e3468795 to your computer and use it in GitHub Desktop.
to_b makes boolean evaluation more deterministic and dependable.
# install in rails: config/initializers/to_b.rb
#
# Examples of how it makes things easier:
#
# true if [] # => true
# true if [].to_b # => nil
# true if "" # => true
# true if "".to_b # => nil
# true if 0 # => true
# true if 0.to_b # => nil
# true if "false" # => true
# true if "false".to_b # => nil
#
# In the first and second example, an empty array or an empty string evaluates as true and I almost always
# want that to be evaluated as false.
# In the third example, 0 (zero) is still a numeric value and will evaluate as true, to_b evaluates that as false.
# In the fourth example, rails will often return a string, not a boolean so to_b looks at the string and
# evaluates more appropriately.
#
# You can attach to_b to pretty much any object and it will evaluate true or false as dependable as possible.
#
class Object
def to_b
return self.count > 0 if self.is_a?(Array)
return self.present? if self.is_a?(MatchData)
if (count = self.count rescue false)
return count > 0
end
return true if self.is_a?(Integer) && self > 0 rescue nil
self.to_s.match(/(true|t|yes|y|1)$/i) != nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment