Created
December 31, 2009 20:39
-
-
Save aquabu/266901 to your computer and use it in GitHub Desktop.
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
def to_boolean(value, nil_value = false) | |
value.downcase! if value.class == String | |
case value | |
when "no","false",false, "0", 0 | |
false | |
when "yes","true",true, "1", 1 | |
true | |
when nil | |
nil_value | |
else | |
!!value | |
end | |
end | |
describe "#to_boolean" do | |
it "converts false values" do | |
["no","false",false, "0", 0].each do |value| | |
to_boolean(value).should == false | |
end | |
end | |
it "converts true values" do | |
["yes","true",true, "1", 1].each do |value| | |
to_boolean(value).should == true | |
end | |
end | |
it "is case insensitive for strings" do | |
to_boolean("YeS").should == true | |
to_boolean("NO").should == false | |
to_boolean("TruE").should == true | |
to_boolean("FalSe").should == false | |
end | |
it "converts nil to false by default" do | |
to_boolean(nil).should == false | |
end | |
it "can return nil as nil" do | |
to_boolean(nil, nil).should == nil | |
end | |
it "converts unmatched strings to true" do | |
to_boolean("a string").should == true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment