-
-
Save mayuresh-srivastava/15ff6cbda04767027ecf82b8e60a3f4d to your computer and use it in GitHub Desktop.
String "false" to_bool ... or how to convert Rails/SimpleForm radio buttons to boolean
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
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 |
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
# However there is also better practice to do it by using | |
ActiveRecord::ConnectionAdapters::Column.value_to_boolean( something ) | |
2.0.0dev :019 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean('1') | |
=> true | |
2.0.0dev :020 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean('0') | |
=> false | |
2.0.0dev :021 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean('true') | |
=> true | |
2.0.0dev :022 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean('false') | |
=> false | |
2.0.0dev :023 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean('nil') | |
=> false | |
2.0.0dev :024 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean('t') | |
=> true | |
2.0.0dev :025 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean('cat') | |
=> false | |
2.0.0dev :026 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean(true) | |
=> true | |
2.0.0dev :027 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean(false) | |
2.0.0dev :035 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean(1) | |
=> true | |
2.0.0dev :036 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean(2) | |
=> false | |
2.0.0dev :037 > ActiveRecord::ConnectionAdapters::Column.value_to_boolean(0) | |
=> false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment