Skip to content

Instantly share code, notes, and snippets.

@aquabu
Created December 31, 2009 20:39
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 aquabu/266901 to your computer and use it in GitHub Desktop.
Save aquabu/266901 to your computer and use it in GitHub Desktop.
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