support "on" and "off" when converting string to boolean

This commit is contained in:
Havoc Pennington 2011-11-16 10:34:40 -05:00
parent 61b1281e90
commit 20b75542e4
3 changed files with 21 additions and 7 deletions

View File

@ -652,11 +652,11 @@ implementation should attempt to convert types as follows:
representation that would be a valid number in JSON.
- boolean to string: should become the string "true" or "false"
- string to number: parse the number with the JSON rules
- string to boolean: the strings "true", "yes", "false", "no"
should be converted to boolean values. It's tempting to
support a long list of other ways to write a boolean, but
for interoperability and keeping it simple, it's recommended to
stick to these four.
- string to boolean: the strings "true", "yes", "on", "false",
"no", "off" should be converted to boolean values. It's
tempting to support a long list of other ways to write a
boolean, but for interoperability and keeping it simple, it's
recommended to stick to these six.
- string to null: the string `"null"` should be converted to a
null value if the application specifically asks for a null
value, though there's probably no reason an app would do this.

View File

@ -31,9 +31,10 @@ final class DefaultTransformer {
return new ConfigNull(value.origin());
break;
case BOOLEAN:
if (s.equals("true") || s.equals("yes")) {
if (s.equals("true") || s.equals("yes") || s.equals("on")) {
return new ConfigBoolean(value.origin(), true);
} else if (s.equals("false") || s.equals("no")) {
} else if (s.equals("false") || s.equals("no")
|| s.equals("off")) {
return new ConfigBoolean(value.origin(), false);
}
break;

View File

@ -422,4 +422,17 @@ class ConfigValueTest extends TestUtils {
assertEquals(Int.MaxValue + 1L, nD(Int.MaxValue + 1.0).unwrapped())
assertEquals(Int.MinValue - 1L, nD(Int.MinValue - 1.0).unwrapped())
}
@Test
def automaticBooleanConversions() {
val trues = parseObject("{ a=true, b=yes, c=on }")
assertEquals(true, trues.getBoolean("a"))
assertEquals(true, trues.getBoolean("b"))
assertEquals(true, trues.getBoolean("c"))
val falses = parseObject("{ a=false, b=no, c=off }")
assertEquals(false, falses.getBoolean("a"))
assertEquals(false, falses.getBoolean("b"))
assertEquals(false, falses.getBoolean("c"))
}
}