Skip to content

Instantly share code, notes, and snippets.

@Genkilabs
Created November 23, 2015 20:31
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 Genkilabs/ba4587cd3877dc6016e4 to your computer and use it in GitHub Desktop.
Save Genkilabs/ba4587cd3877dc6016e4 to your computer and use it in GitHub Desktop.
Add a 'to_bool' method to every Ruby / Rails class with initializer
#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