Skip to content

Instantly share code, notes, and snippets.

@vishalzambre
Last active November 12, 2020 09:16
Show Gist options
  • Save vishalzambre/b85b8b43dab8fb7f3c76e295a1f5104f to your computer and use it in GitHub Desktop.
Save vishalzambre/b85b8b43dab8fb7f3c76e295a1f5104f to your computer and use it in GitHub Desktop.
Ruby String to Boolean
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
@vishalzambre
Copy link
Author

In Rails same result can be achieved by ActiveModel::Type::Boolean.new.cast('t')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment