Skip to content

Instantly share code, notes, and snippets.

@joe1chen
Forked from equivalent/README.md
Created November 21, 2012 20:44
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 joe1chen/4127547 to your computer and use it in GitHub Desktop.
Save joe1chen/4127547 to your computer and use it in GitHub Desktop.
String "false" to_bool ... or how to convert Rails/SimpleForm radio buttons to boolean
module StringToBoolean
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
class String; include StringToBoolean; end
module BooleanToBoolean
def to_bool;return self; end
end
class TrueClass; include BooleanToBoolean; end
class FalseClass; include BooleanToBoolean; end
@joe1chen
Copy link
Author

It turns out that if you're using Mongoid, then Boolean is declared as a class inside of Mongoid. This prevents the original gist from working if using Mongoid since we're trying to redefine Boolean as a module. So the original gist has been modified to rename the module Boolean to BooleanToBoolean.

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