diff --git a/spec/config-spec.coffee b/spec/config-spec.coffee index d2a2ec9b3..dd408bd44 100644 --- a/spec/config-spec.coffee +++ b/spec/config-spec.coffee @@ -508,6 +508,22 @@ describe "Config", -> atom.config.set('foo.bar.anInt', 'nope') expect(atom.config.get('foo.bar.anInt')).toBe 12 + describe 'when the minimum and maximum keys are used', -> + beforeEach -> + schema = + type: 'integer' + minimum: 10 + maximum: 20 + default: 12 + atom.config.setSchema('foo.bar.anInt', schema) + + it 'keeps the specified value within the specified range', -> + atom.config.set('foo.bar.anInt', '123') + expect(atom.config.get('foo.bar.anInt')).toBe 20 + + atom.config.set('foo.bar.anInt', '1') + expect(atom.config.get('foo.bar.anInt')).toBe 10 + describe 'when the value has an "integer" and "string" type', -> beforeEach -> schema = @@ -540,6 +556,22 @@ describe "Config", -> atom.config.set('foo.bar.aFloat', 'nope') expect(atom.config.get('foo.bar.aFloat')).toBe 12.1 + describe 'when the minimum and maximum keys are used', -> + beforeEach -> + schema = + type: 'number' + minimum: 11.2 + maximum: 25.4 + default: 12.1 + atom.config.setSchema('foo.bar.aFloat', schema) + + it 'keeps the specified value within the specified range', -> + atom.config.set('foo.bar.aFloat', '123.2') + expect(atom.config.get('foo.bar.aFloat')).toBe 25.4 + + atom.config.set('foo.bar.aFloat', '1.0') + expect(atom.config.get('foo.bar.aFloat')).toBe 11.2 + describe 'when the value has a "boolean" type', -> beforeEach -> schema = diff --git a/src/config.coffee b/src/config.coffee index 8f1c86080..482c40f4c 100644 --- a/src/config.coffee +++ b/src/config.coffee @@ -404,12 +404,26 @@ Config.addTypeFilters throw new Error() if isNaN(value) value + minMaxCoercion: (value, schema) -> + if schema.minimum? and typeof schema.minimum is 'number' + value = Math.max(value, schema.minimum) + if schema.maximum? and typeof schema.maximum is 'number' + value = Math.min(value, schema.maximum) + value + 'number': coercion: (value, schema) -> value = parseFloat(value) throw new Error() if isNaN(value) value + minMaxCoercion: (value, schema) -> + if schema.minimum? and typeof schema.minimum is 'number' + value = Math.max(value, schema.minimum) + if schema.maximum? and typeof schema.maximum is 'number' + value = Math.min(value, schema.maximum) + value + 'boolean': coercion: (value, schema) -> switch typeof value @@ -419,7 +433,7 @@ Config.addTypeFilters !!value 'string': - typeCheck: (value, schema) -> + coercion: (value, schema) -> throw new Error() if typeof value isnt 'string' value