Last active
November 12, 2020 09:16
-
-
Save vishalzambre/b85b8b43dab8fb7f3c76e295a1f5104f to your computer and use it in GitHub Desktop.
Ruby String to Boolean
This file contains hidden or 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
module StringToBooleanRefinementsService | |
refine String do | |
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, "invalid value for Boolean: \"#{self}\"" | |
end | |
alias_method :to_b, :to_bool | |
end | |
end | |
# Include to your class where change wanted. | |
class StringExample | |
using StringToBooleanRefinementsService | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In Rails same result can be achieved by
ActiveModel::Type::Boolean.new.cast('t')