Created
July 23, 2019 16:53
-
-
Save kares/8a57d805d3fb8c6580e193974d174bb5 to your computer and use it in GitHub Desktop.
`params[:foo].to_bool`, `ENV['bar'].to_bool` and others
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
class Object | |
# Convert to a boolean value (special cased for String/Numeric). | |
# @return [Boolean] false for nil and false ('true', '1' return true and 0 returns false) | |
# @see String#to_bool | |
# @see Numeric#to_bool | |
def to_bool | |
!!self | |
end | |
end | |
class String | |
# @return [Boolean] 'true' and '1' are considered truthy | |
def to_bool | |
'true'.casecmp(self).zero? || '1'.eql?(self) | |
end | |
end | |
class Numeric | |
# @return [Boolean] false for 0, true otherwise | |
def to_bool | |
!zero? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment