Created
November 23, 2015 20:31
-
-
Save Genkilabs/ba4587cd3877dc6016e4 to your computer and use it in GitHub Desktop.
Add a 'to_bool' method to every Ruby / Rails class with initializer
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
#Alias the default boolean? operator of ruby for everything so all objects responds_to? :to_bool | |
#...then further refine it for specific classes later | |
class Object | |
def to_bool | |
return !!self | |
end | |
end | |
#Lets give String a custom to_bool that is in line with the meaning for our specific program | |
class String | |
def to_bool | |
return true if self == true || self =~ (/(true|t|yes|y|1)$/i) | |
return false if self == false || self.blank? || self =~ (/(false|f|no|n|0)$/i) | |
raise ArgumentError.new("invalid value for Boolean: \"#{self}\"") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment